小程序上传图片缓存到本地

故事扮演 提交于 2019-12-01 20:59:13

今日写小程序上传图片时遇到了点困难,图片上传到接口保存到数据库,用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) {},
    })

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!