一.小程序
1.wxml代碼
<view>
<button bindtap='fileUploadTap'>上傳</button>
</view>
2.js代碼
fileUploadTap: function(){
wx.chooseImage({
success(res) {
const tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'http://localhost:8080/upload', //僅為示例,非真實的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData: {
description: '圖片'
},
success(res) {
console.log(res.data)
}
})
}
})
}
3.演示界面

image.png
點擊上傳按鈕,就可以選擇相應的圖片進行上傳
二.springboot后端
@RestController
public class TestController {
// 上傳文件會自動綁定到MultipartFile
@PostMapping(value="/upload")
public String upload(HttpServletRequest request,
@RequestParam("description") String description,
@RequestParam("file") MultipartFile file) throws Exception{
//接收參數(shù)description
System.out.println("description: " + description);
//如果文件不為空,寫入上傳路徑
if (!file.isEmpty()){
//上傳文件路徑
String path = request.getServletContext().getRealPath("/upload/");
System.out.println("path = " + path);
//上傳文件名
String filename = file.getOriginalFilename();
File filePath = new File(path, filename);
//判斷路徑是否存在,如果不存在就創(chuàng)建一個
if (!filePath.getParentFile().exists()){
filePath.getParentFile().mkdirs();
}
//將上傳文件保存到一個目標文件當中
file.transferTo(new File(path+File.separator + filename));
System.out.println(filename);
return "success";
}else {
return "error";
}
}
}