微信小程序利用oss 上传图片到阿里云 上传进度及失败处理 判断上传图片格式

业务需求场景分析:

	我们的项目需求是用户上传自己的拍摄的图片到阿里云服务器,目前是每次上传一张

实现过程分析

	首先微信公众平台官方给出了上传图片的API    wx.chooseImage
	然后根据调用成功后的success事件中通过拿到的文件名称,先做一个判断,
	格式是否正确,格式不正确弹框提示并返回(为了更加准确的判断,先对所有格式的后缀名变更为大写,然后再统一做比较)。
	上传文件格式正确,则发送请求获取policy参数,对参数进行处理(文件名),然后发送请求至阿里云,url  为后台给的参数中的host参数,
	如果 res.resultCode==200,代表上传成功
具体代码如下:
	如有疑问,欢迎交流
chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1,  //设定每次最多能上传几张,最多9张
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths;
        let imgFile = res.tempFiles;
        let extStart = imgFile[0].path.lastIndexOf(".")
        let imageName = imgFile[0].path;
        let ext = imageName.substring(extStart, imageName.length).toUpperCase();
        //判断图片格式
        if (ext !== '.PNG' && ext !== '.JPG' && ext !== '.JPEG' && ext !== '.GIF') {
          wx.showModal({
            content: '图片格式不正确,请重新选择',
            showCancel: false
          })  
          return false;
        }
        for (let i = 0; i < tempFilePaths.length; i++) {
          let n = tempFilePaths[i].lastIndexOf('.');
          let type = tempFilePaths[i].substring(n);
          console.log("type==="+type)
          let policyUrl = app.globalData.baseUrl + app.globalData.http.getOssInfo + "?memberId=" + wx.getStorageSync("memberId")
          wx.request({
            url: policyUrl, //获取oss签名
            success: function (res) {
              wx.showLoading({ title: '图片上传中' });
              if (res.data.resultCode == 200) {
                let post = res.data.data.info;
                console.log(post.host)
                let foot1 = 'x-oss-process=image/resize,w_1080,h_1920,m_fill/watermark,type_d3F5LXplbmhlaQ,size_38,text_'
                const aliyunFileKey = post.dir + "/" + post.fileName + type;
                let showUrl = null;
                wx.uploadFile({
                  url: post.host, //上传到OSS
                  filePath: tempFilePaths[i],
                  name: 'file',
                  formData: {
                    'key': aliyunFileKey,
                    'OSSAccessKeyId': post.accessKeyId,
                    'policy': post.policy,
                    'signature': post.signature,
                    'success_action_status': '200',
                  },                  
                  success: function (res) {                    
                    if (res.statusCode == 200) {
                      wx.hideLoading()
                      wx.showToast({
                        title: '上传成功',
                        icon: 'success',
                        duration: 1200
                      })                      
                      showUrl = post.host + '/' + aliyunFileKey
                      that.setData({
                        files: showUrl
                      });
                      console.log(showUrl)
                    } else {
                      wx.showToast({
                        title: '上传失败!',
                        icon: 'none',
                        duration: 1200
                      })
                    }
                  }
                })
              }
            },
            fail: function(res){
              console.log(res)
            }
          })
        }
      }
    })
  }, 

猜你喜欢

转载自blog.csdn.net/Taurus_0811/article/details/88619532