微信小程序 ——上传图片

chooseImage(){
  const that = this;
  wx.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success (res) {
      console.log('选择图片的信息', res);
      if(res.tempFiles[0].size > 512000 ){
        wx.showToast({
          title: '图片最大为500kb',
          icon: 'none',
          duration: 2000,
          mask:true
        })
        return false;
      }
      // tempFilePath可以作为img标签的src属性显示图片
      const tempFilePaths = res.tempFilePaths;
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.uploadFile({
        url:`${configApi.baseUrl}${urls.uploadPic}`,
        filePath: tempFilePaths[0],
        name: 'file',
        header: {
          "content-type": "multipart/form-data"
        },
        formData: {
          'user': 'test'
        },
        success(res){
          that.uploadPic = `${configApi.baseUrl}${JSON.parse(res.data).result.imgUrl}`.replace('api/', '');
        },
        fail: function(error) {
          console.log(error);
        },
        complete: function() {
          wx.hideLoading();
        }
      })
      that.$apply();
    }
  })
},

  

posted @ 2020-08-28 11:09  徐林俊  阅读(232)  评论(0编辑  收藏  举报