小程序项目中遇到需要更换用户头像的需求,这里记录下,相关逻辑代码index.ts,只选取重要的如下:

  // 更换用户头像
  changeAvatar() {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],  // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'],  // 可以指定来源是相册还是相机,默认二者都有
      success(res) {
        wx.showLoading({
          title: "上传中...",
          mask: true,
        });
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePath = res.tempFilePaths[0]
        console.log(tempFilePath, res);
        wx.uploadFile({
          url: 'http://192.168.188.226:22000/ech-sad/v1/upload/img', // 上传图片的服务器地址,写自己项目中的即可
          filePath: tempFilePath, // 上传图片的本地路径
          name: 'imagefile',
          header: {
            Authorization: wx.getStorageSync("Authorization"),
          },   // 设置请求头,携带上token
          formData: {
            imagefile: tempFilePath,
            'type': '3',
          }, // 后端需要的请求体参数
          success(resp) {
            wx.hideLoading();
            // 返回的是json字符串类型数据,要转换为json对象
            const json_data = JSON.parse(resp.data)
            const image = json_data.data
            console.log('aaa', image);
            that.setData({
              buttonDisabled: false,
              image
            })
          }
        })
      }
    })
  },
posted on 2021-09-28 14:38  九零菜菜  阅读(738)  评论(1编辑  收藏  举报