1.小程序wxml:
<view><view>准备上传的图片</view><image class="ph" src="{{photoold}}" mode="aspectFit"></image><view><button bindtap="chooseImage" size="mini" type="primary">选择图片</button><button bindtap="uploadImage" size="mini"type="primary" >上传图片</button></view><view>上传后从服务器获取的图片</view><image class="ph" src="https://www.ssdnnc.xyz/{{photonew}}" mode="aspectFit"></image></view>
2.小程序JS:
// pages/instructions/instructions.js
Page({/*** 页面的初始数据*/data: {myopenid:"",photoold:"",photonew:""},//选择图片
chooseImage :function(e){var that = this;wx.chooseImage({success(res){that.setData({photoold:res.tempFilePaths[0]})}})
},
uploadImage :function(e){var that =this;console.log("openid:",that.data.myopenid);console.log("filePath:",that.data.photoold);wx.uploadFile({filePath: that.data.photoold,// 参数名和接口一致name: 'file',url: 'https://www.aaaaa.xyz/user/uploadpicture',formData:{'myopenid': that.data.myopenid,}, success(res){console.log(res.data)that.setData({photonew:res.data+"?temp="+new Date().getTime()})wx.showToast({title: '图片上传成功',icon: 'success',duration: 2000})},fail(res){console.log(res)wx.showToast({title: '图片上传失败',icon: 'error',duration: 2000})}})
},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {this.setData({ myopenid : options.myopenid,})},/*** 生命周期函数--监听页面初次渲染完成*/onReady: function () {},/*** 生命周期函数--监听页面显示*/onShow: function () {},/*** 生命周期函数--监听页面隐藏*/onHide: function () {},/*** 生命周期函数--监听页面卸载*/onUnload: function () {},/*** 页面相关事件处理函数--监听用户下拉动作*/onPullDownRefresh: function () {},/*** 页面上拉触底事件的处理函数*/onReachBottom: function () {},/*** 用户点击右上角分享*/onShareAppMessage: function () {}
})
3.Java后端
//用户上传图片@RequestMapping("/uploadpicture")@ResponseBodypublic String upload2(@RequestParam("file") MultipartFile file , HttpServletRequest request) throws IOException {//上传路径保存设置String openid = request.getParameter("myopenid");System.out.println("openid:"+openid);if(openid!=null){String uploadFileName = file.getOriginalFilename();uploadFileName=openid+getFileType(uploadFileName);System.out.println("上传文件名:"+uploadFileName);//上传路径保存设置//String path = request.getSession().getServletContext().getRealPath("/userpicture/");//写死了,和nginx配置文件里一致String path = "/usr/local/webserver/nginx/image";File realPath = new File(path);if(!realPath.exists()){realPath.mkdir();}System.out.println("上传文件保存地址:"+realPath);InputStream is = file.getInputStream();//文件输入流OutputStream os = new FileOutputStream(new File(realPath,uploadFileName));//文件输出流//读取写出int len=0;byte[] buffer = new byte[1024];while((len=is.read(buffer))!=-1){os.write(buffer,0,len);os.flush();}os.close();is.close();return uploadFileName;}else{return "上传失败!";}}
4.Nginx
location ~ .(jpg|png|jpeg|gif|bmp)$ {root /usr/local/webserver/nginx/image;autoindex on;expires 1h;}
5.演示

6.存在的坑
小程序页面如果多次请求的图片地址相同,图片不会自动更新,清除缓存也没用
解决办法:在URL后面加上时间戳
that.setData({photonew:res.data+"?temp="+new Date().getTime()})