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

业务需求场景分析:

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

实现过程分析
  • 首先微信公众平台官方给出了上传图片的API wx.chooseImage;

  • 然后根据调用成功后的success事件中通过拿到的文件名称,先做一个判断;

  • 格式是否正确,格式不正确弹框提示并返回(为了更加准确的判断,先对所有格式的后缀名变更为大写,然后再统一做比较);

  • 上传文件格式正确,则发送请求获取policy参数,对参数进行处理(文件名),然后发送请求至阿里云,url 为后台给的参数中的host参数;

  • 获取上传进度 UploadTask.onProgressUpdate(function callback)

  • 如果 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;
                const uploadTask = 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)
            }
          })
          // 获取上传进度
          uploadTask.onProgressUpdate((res) => {
			  console.log('上传进度', res.progress)
			  console.log('已经上传的数据长度', res.totalBytesSent)
			  console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
		  })
			
		  //uploadTask.abort() // 如有需要 可以取消上传任务
        }
      }
    })
  }, 
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

【拾光静好 微微一笑】

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值