spring boot+uniapp上傳單個檔案
阿新 • • 發佈:2022-04-13
後端程式碼:檔案上傳位置為/static/photo目錄下
@PostMapping("save") public int savePicture(@RequestParam("file")MultipartFile file,@RequestParam("id")String id) throws IOException { //如果檔案不存在上傳失敗 if (file.isEmpty()) { System.out.println("檔案不存在"); return 0; } //獲取檔名字 String fileName = file.getOriginalFilename(); //設定編譯後文件存在路徑 String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/photo/"; //獲取專案路徑 File directory = new File("src/main/resources/static/photo"); String paths = directory.getCanonicalPath(); File dest = new File(paths+'/' + fileName); System.out.println(dest.getAbsoluteFile()); FileInputStream fileInputStream = (FileInputStream) file.getInputStream(); //以流的方式上傳 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName)); byte[] bs = new byte[1024]; int len; while ((len = fileInputStream.read(bs)) != -1) { bos.write(bs, 0, len); } bos.flush(); bos.close(); try { //檔案上傳 file.transferTo(dest); return 1; } catch (IOException e) { } return 1; }
前端程式碼為
<template> <view class="container"> <view>首頁</view> <view>上傳檔案測試</view> <button type="primary" @click="uploadFile">點選上傳檔案</button> </view> </template> <script> export default { data() { return { id:"20181008093" } }, methods: { uploadFile(){ var _this=this; uni.chooseImage({ success(res) { console.log(res) var tempFilePath=res.tempFilePaths; uni.uploadFile({ url:'http://localhost:9000/save', filePath:tempFilePath[0], name:"file", formData:{ "id":_this.id }, success(res) { console.log(res.data) } }) } }) } } } </script> <style> .container { padding: 20px; font-size: 14px; line-height: 24px; } </style> ```html