Mini program upload pictures, form-data upload, and base64 upload

Background requires format:

Just use the official upload function of the applet directly

updataimg() {//上传图片
    let url = app.$api.hostUrl()
    let that = this;
    wx.chooseImage({
      sourceType: ["camera"],
      success:res => {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          images: tempFilePaths
        })
        let query = {
          businessId: that.data.unRedeemCoupon.couponId,//业务主键
          businessType: 'YHQ',//业务类别,配合businessId形成唯一业务标识,只接受字母,必填
          businessName: '优惠券',//业务描述,例如图片/文件名称等,可以用于业务判断,非必填
          // mFiles: [tempFilePaths]
        }
        
        let hostUrl = app.$api.hostUrl()
        wx.uploadFile({
          url: `${hostUrl}/pricing-user/file/upload`, // 上传的服务器接口地址
          filePath: res.tempFilePaths[0],
          name: 'mFiles', //上传的所需字段,后端提供
          header: {
            'X-TOKEN': token
          },
          formData: query,
          success: (ress) => {
            if (ress.data){
              let da=JSON.parse(ress.data)
              if (da.code == 0) {
                that.setData({
                  fullFilePath: da.data[0].fullFilePath
                })
                wx.showToast({
                  title: '上传成功',
                  icon: 'none',
                  duration: 3000
                })
              } else {
                wx.showToast({
                  title: da.data,
                  icon: 'none',
                  duration: 3000
                })
              }
            }
          },
          fail: (err) => {
            wx.showToast({
              title: '上传失败',
              icon: 'none',
              duration: 3000
            })
          }
        });
      }
    })
  },

 The following is the base64 image upload:

 updataimg() {//上传图片
    let url = app.$api.hostUrl()
    wx.chooseImage({
      sourceType: ["camera"],
      success:res => {
        const tempFilePaths = res.tempFilePaths;
        this.setData({
          images: tempFilePaths
        })
        // let base =  'data:image/png;base64,' + wx.getFileSystemManager().readFileSync(res.tempFilePaths[0], 'base64')
        console.log(base)
      }
    })
  },

Note: The pictures accepted by this conversion method in the background cannot be opened, and they may be used in the future if they are kept temporarily

These two methods are processed into blob file format. If you don’t need blob format, you don’t need these two methods. 

//生成分割字符串
const generateDivisionStr= () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
      let r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8)
      return v.toString(16);
    })
  }
  //上传图片封装上传所需参数
const generateUploadParams=(str, obj)=> {
  let pra = ''
  Object.keys(obj).forEach(key => {
    //如果是ArrayBuffer类型的图片文件
    if (typeof obj[key] === "object") {
      //随机图片文件名
      let iName = generateDivisionStr()
      pra += `\r\n--${str}` +
        `\r\nContent-Disposition: form-data; name="${key}";filename="${iName}.png"` +
        `\r\nContent-Type: "image/png"` +
        `\r\n` +
        `\r\n${obj[key]}`
    } else {
      pra += `\r\n--${str}` +
        `\r\nContent-Disposition: form-data; name="${key}"` +
        `\r\n` +
        `\r\n${obj[key]}`
    }
  })
  pra = pra + `\r\n--${str}--`
  return pra
}

Guess you like

Origin blog.csdn.net/qq_36821274/article/details/126242475