后台Java代码加前端微信小程序实现图片上传案例(学习)
//后台实现上传的方法
/*
上传方法所要用到的第三方工具类的包
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*/
private static final Logger LOG = LoggerFactory
.getLogger(PublicIndexController.class);//PublicIndexController 该controller控制器的名字
@PostMapping("/fileUpload") public String uploadMusicFile(HttpServletRequest request,@RequestParam("file")MultipartFile[] files){ LOG.info("进入上传..."); String uploadPath="D:/tempFile/";//存放到本地路径(示例) if(files!=null && files.length>=1) { BufferedOutputStream bw = null; try { String fileName = files[0].getOriginalFilename(); //判断是否有文件 if(StringUtils.isNoneBlank(fileName)) { //输出到本地路径 File outFile = new File(uploadPath + UUID.randomUUID().toString()+getFileType(fileName)); LOG.info("path=="+uploadPath + UUID.randomUUID().toString()+ getFileType(fileName)); FileUtils.copyInputStreamToFile(files[0].getInputStream(), outFile); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(bw!=null) {bw.close();} } catch (IOException e) { e.printStackTrace(); } } } return "success"; } public static String getFileType(String filename){ if(filename.endsWith(".jpg") || filename.endsWith(".jepg")){ return ".jpg"; }else if(filename.endsWith(".png") || filename.endsWith(".PNG")){ return ".png"; } else{ return "application/octet-stream"; } }
//微信端小程序wxml页面代码
<view class='container'> <form > <view class='row'> <input type='text' name='file'bindtap='startUpload' placeholder='请选择上传的文件'/> </view> <!-- <view > <button bindtap='upload' class="aa">上传</button> </view> --> </form> </view>
//微信端小程序js上传代码
startUpload: function () { wx.chooseImage({ success: function (res) { var tempFilePaths = res.tempFilePaths console.log(tempFilePaths) wx.uploadFile({ url: 'http://192.168.1.101:8085/public/index/fileUpload', //仅为示例,非真实的接口地址 filePath: tempFilePaths[0], name: "file", header: { "Content-Type": "multipart/form-data" }, formData: { "user": "test", }, // success: function (res) { // var data = res.data // console.log(data) // //do something // }, success: function (res) { console.log(res, '6666'); if (res.statusCode = 200) { wx.showModal({ title: '提示', content: '上传成功', showCancel: false }) return; } var data = res.data // page.setData({ //上传成功修改显示头像 // src: path[0] // }) }, fail: function (e) { console.log(e); wx.showModal({ title: '提示', content: '上传失败', showCancel: false }) }, }) } }) }
结:便于以后学习工作用到,可用于做参考