小程序上传图片到腾讯云
发布于 6 年前 作者 fangluo 9020 次浏览 来自 问答

谁有这方面的经验,急急急!

可参考:

https://segmentfault.com/a/1190000010872161

https://cloud.tencent.com/document/product/436/31953

自己尝试过了,无果!

求大神指点!

有前端代码更好!

以下是后端提供的接口文档:

https://www.showdoc.cc/337721710807897?page_id=1945096138647259

以下为h5端上传到腾讯云的代码:

1 回复
/*
uploadFile 上传文件公共方法
[@params](/user/params): successCb 回调函数
*/
uploadFile: function(successCb, index) {
  var that = this;
  wx.chooseImage({
    count: 1, // 默认9
    sizeType: ["compressed"], // 可以指定是原图还是压缩图,默认二者都有
    sourceType: ["album", "camera"], // 可以指定来源是相册还是相机,默认二者都有
    success: function(res) {
      // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
      var tempFilePaths = res.tempFilePaths;
      var tempFilesSize = res.tempFiles[0].size; //获取图片的大小,单位B
      if (tempFilesSize <= 3000000) {
        //图片小于或者等于3M时 可以继续
        that.uploadImgFile(that, tempFilePaths, successCb, index);
      } else {
        wx.showToast({
          title: "上传图片不能大于3M哦~",
          icon: "none"
        });
      }
    }
  });
},
uploadImgFile: function(page, path, successCb, index) {
  wx.showLoading({
    title: "上传中...",
    mask: true
  });
  wx.uploadFile({
    url: 'xxx',
    filePath: path[0],
    name: "image",
    header: {
      chartset: "utf-8",
      "content-type": "multipart/form-data"
    },
    formData: {
      token: wx.getStorageSync('token')
    },
    success: function(res) {
      if (res.statusCode !== 200) {
        wx.showModal({
          title: "提示",
          content: "上传失败,请稍后重试",
          showCancel: false
        });
        return;
      } else {
        let data = JSON.parse(res.data);
        try {
          let data = JSON.parse(res.data);
          if (data.success) {
            console.log(index);
            successCb && successCb(data.data, index);
          } else {
            wx.showModal({
              title: "提示",
              content: res.msg || "上传失败,请稍后重试",
              showCancel: false
            });
            return;
          }
        } catch (err) {
          wx.showModal({
            title: "提示",
            content: "上传失败,请稍后重试",
            showCancel: false
          });
          return;
        }
      }
    },
    fail: function(e) {
      wx.showModal({
        title: "提示",
        content: "上传失败,请稍后重试",
        showCancel: false
      });
    },
    complete: function() {
      wx.hideLoading();
    }
  });
},
回到顶部