微信小程序文件上传 Java(附代码)
微信小程序+Springboot实现文件上传
微信小程序代码
API接口:
1.从客户端选择文件:wx.chooseMessageFile
使用方法:
wx.chooseMessageFile({ count: 10, type: \'image\', success (res) { // tempFilePath可以作为img标签的src属性显示图片 const tempFilePaths = res.tempFiles } })
2.上传文件:wx.uploadFile
使用方法:
wx.chooseImage({ success (res) { const tempFilePaths = res.tempFilePaths wx.uploadFile({ url: \'https://example.weixin.qq.com/upload\', //仅为示例,非真实的接口地址 filePath: tempFilePaths[0], name: \'file\', formData: { \'user\': \'test\' }, success (res){ const data = res.data //do something } }) } })
upload.wxml
1 <view> 2 <button bindtap="upImage">上传图片</button> 3 </view> 4 <view> 5 <button bindtap="upFile">上传文件</button> 6 </view>
upload.js
upImage: function() { wx.chooseImage({ count: 1, sizeType: [\'original\', \'compressed\'], sourceType: [\'album\', \'camera\'], success: function(res) { const tempFilePaths = res.tempFilePaths wx.uploadFile({ url: \'http://localhost/picture\', filePath: tempFilePaths[0], name: \'file\', success(res) { console.log("success") console.log(res) }, fail(res) { console.log("失败") console.log(res) } }) }, }) }, upFile: function() { wx.chooseMessageFile({ count: 1, type: \'file\', success(res) { const tempFilePaths = res.tempFiles wx.uploadFile({ url: \'http://localhost/picture\', filePath: tempFilePaths[0].path, name: \'file\', success(res) { console.log("success") console.log(res) }, fail(res) { console.log("失败") console.log(res) } }) } }) },
Java代码
upload.java
@RequestMapping(value = "/picture", method = RequestMethod.POST) public String uploadPicture(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile files) throws Exception { try { System.out.println("图片上传请求成功"); String type = files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf(".")); String path = "E:/demo/image/upload"; File fileParent = new File(path); if (!fileParent.exists()) { fileParent.mkdirs(); } File targetFile = new File(path + "/", files.getOriginalFilename()); if (!targetFile.exists()) { targetFile.createNewFile(); } files.transferTo(targetFile); return files.getOriginalFilename(); } catch (Exception e) { return "上传失败"; } }
服务器配置注意项
如果抛出以下异常请检查域名配置是否正确
如果域名配置正确并且 wx.uploadFile 中 url 参数准确无误尝试以下办法