微信小程序项目需要用户选择文件上传文件到服务器,折腾了好大一会,参考了网上的代码,并略微修改,方便自己,也方便别人,记录下来
1.微信小程序代码
.wxml
<view class="usermotto"><text class="user-motto" bindtap="saveFile">{{motto}}</text></view>
.js
saveFile() {wx.chooseMedia({count: 1, // 可选文件数量。因为是头像上传,只一个文件就可mediaType: ["image"], // 文件类型:这里只是图片,其他使用看官网success: res => {this.uploadFile(res.tempFiles[0]); // 返回的数据里有我们后面上传需要的文件,保存下来},fail: err => {console.log(err, "personal.js >>>> 个人资料 上传头像")}})},uploadFile(file) {//console.log(file.tempFilePath);wx.uploadFile({filePath: file.tempFilePath, // 上一步操作中带过来的文件name: 'file', // 接口中要求的formData类型数据的参数url: 'http://localhost:8080/handle-video/common/uploadFile', // 接口formData: { // 其他数据类型的参数code: '',type: ''},success: res => {console.log(res,'上传成功');},fail: err => {console.log(err, 'personal.js >>>> 个人资料')}})
2.java代码
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;@RestController
@RequestMapping("/handle-video/common")
public class CommonController {@RequestMapping("/uploadFile")public String uploaddFie(MultipartFile file){return file.getOriginalFilename();}
}
参考文档1:微信上传 wx.chooseMedia和wx.uploadFile使用,java springboot后端跑通_老饼干的博客-CSDN博客
参考文档2:https://www.jianshu.com/p/49227427d145