微信小程序封装图片上传到untils

1.uploadImg.js

/**
 * 上传图片方法
 */
const uploadImg = (url, storageName, fn, count = 1,formData = {} )=>{
  wx.chooseImage({
    count: count,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: function (res) {
      //通过打印,这里面就两个数组,都是路径,其中一个还有一个size属性
      var imgPath = res.tempFilePaths[0];
      // that.setData({
      //   idcardFront: imgPath
      // })
      //这里需要操作你页面里面的数据怎么办?让你页面自己实现去,只需要把这个方法给我就好了
      fn(imgPath)
      //上传至服务器
      wx.uploadFile({
        url: getApp().globalData.baseUrl + url,//地址
        filePath: imgPath,
        name: 'file',//文件对应的 key,开发者在服务端可以通过这个 key 获取文件的二进制内容
        formData: formData,
        header: {
          'content-type': 'multipart/form-data'
        },
        success(res) {
          let data = JSON.parse(res.data);
          if (res.statusCode != 200 || !data.succ) {
            that.setData({
              imgPath: ''
            })
            wx.showModal({
              title: '',
              content: res.data.errMsg || "上传失败,请重新上传!",
            })
          } else {
            wx.setStorageSync('', imgPath);
          }
        },
        fail: function () {
          wx.showModal({
            content: '请求超时!请检查当前网络!',
            showCancel: false,
            success(res) { }
          })
        }
      })
    }
  })
}
export default uploadImg;

2.引用之后调用

        fn = (imgPath) => {
          this.setData({
            idcardFront: imgPath
          })
        }
        uploadImg("url", "idcardFront", fn);

这里面的回调函数是一个小亮点,把本页面的data数据操作留在了本页面,最后给照片上传一个方法 让它执行。

你可能感兴趣的:(微信小程序)