今日写小程序上传图片时遇到了点困难,图片上传到接口保存到数据库,用tp5直接接收name传参进行正常的上传文件操作就行,但是如何让小程序上传的图片在刷新页面之后还能继续存在呢,这问题着实让我苦恼了一阵子,最后终于在朋友的提醒下成功了,哈哈哈哈
解决办法:
用小程序的数据缓存接口 wx.setStorageSync(KEY,DATA) 存到本地缓存,然后页面加载的时候用 wx.getStorageSync(KEY) 取出来就可以啦
下面上代码
//选择头像 wx.chooseImage({ count: 1, sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function(res) { // console.log(res) var filepath = res.tempFilePaths // console.log(filepath) // 上传头像 wx.uploadFile({ url: getApp().data.url + 'member/imgVipbaseInfo?openid='+wx.getStorageSync('openid'),//这是往后端传参调接口将图片插入数据库的 filePath: filepath[0],//要上传文件的资源路径 name: 'photo',//文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 success: function(res) { // console.log(res) //下载到本地 wx.downloadFile({ url: filepath[0],//文件资源路径 success:function(res){ var tempFilePaths = res.tempFilePath wx.saveFile({ tempFilePath: tempFilePaths,//需要保存的文件的临时路径 success: function (res) { var savedFilePath = res.savedFilePath //console.log(savedFilePath) wx.setStorageSync('img', savedFilePath);//将图片路径缓存到本地 that.setData({ photo: wx.getStorageSync('img')//成功后重新赋值img,之后在页面重新加载的时候再赋值一次就ok啦 }) } }) } }) // console.log(that) if (res.statusCode==200){ wx.showToast({ title: '上传成功', icon: 'success', duration: 1500 }) }else{ wx.showToast({ title: '上传失败', icon: 'none', duration: 1500 }) } }, fail: function(res) {}, complete: function(res) {}, }) }, fail: function(res) {}, complete: function(res) {}, })小程序













