一.小程序
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.演示界面
点击上传按钮,就可以选择相应的图片进行上传
二.springboot后端
@RestController
public class TestController {
// 上传文件会自动绑定到MultipartFile
@PostMapping(value="/upload")
public String upload(HttpServletRequest request,
@RequestParam("description") String description,
@RequestParam("file") MultipartFile file) throws Exception{
//接收参数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);
//判断路径是否存在,如果不存在就创建一个
if (!filePath.getParentFile().exists()){
filePath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件当中
file.transferTo(new File(path+File.separator + filename));
System.out.println(filename);
return "success";
}else {
return "error";
}
}
}