微信小程序 关于头像上传,showActionSheet,chooseImage,uploadFile

微信小程序关于头像上传以及相关的几个API(showActionSheet,chooseImage和uploadFile)

近期参与一个微信小程序的开发,有关于上传头像的需求。在实现后,想写下博客记录一下,也希望能帮到有需要的朋友。

效果预览

点击该区域,可以弹出菜单选择
在这里插入图片描述

在这里插入图片描述

js代码

changeAvatarSheet函数

  // About Change Avatar of users
  // 1.换头像的途径菜单 wx.showActionSheet,选择菜单
  // 调用wx.showActionSheet,作选择菜单
  changeAvatarSheet: function () {
    
    
    var that = this;
    wx.showActionSheet({
    
    
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function (res) {
    
    
        if (!res.cancel) {
    
    
          if (res.tapIndex == 0) {
    
    
            //从相册中选择
            // console.log(res.tapIndex);
            // 调用函数
            that.chooseWxImageShop('album');
          } else if (res.tapIndex == 1) {
    
    
            //手机拍照
            // console.log(res.tapIndex);
            // 调用函数
            that.chooseWxImageShop('camera');
          }
        }
      }
    })
  },
 

chooseWxImageShop函数

  // 2.换头像 wx.chooseImage
  // 3.上传头像到数据库 wx.uploadFile
  chooseWxImageShop: function (type) {
    
    
    var that = this;
    wx.chooseImage({
    
    
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function (res) {
    
    
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
    
    
          filePath: tempFilePaths[0],
          name: 'avator',
          url: 'url',
          header: {
    
    
            'content-type': 'multipart/form-data',
            'X-AUTH-TOKEN': wx.getStorageSync('token')
          }, // 设置请求的 header
          formData: {
    
    
            // 'content-type': 'multipart/form-data',
            // 'user_id': '201825010512',
            // 'filePath': tempFilePaths[0],
          },
          success(res) {
    
    
            // const data = res.data
            var data = JSON.parse(res.data)
            console.log(res.data)
            //do something
            // that.setData({
    
    
            //   app.globalData.userInfo.avatarUrl: data.face_url
            // });
            console.log(data.face_url)
            app.globalData.userInfo.avatarUrl=data.face_url
            console.log(app.globalData.userInfo.avatarUrl)
            wx.showToast({
    
    
              title: '上传成功',
            })
          },
          fail: function (res) {
    
    
            wx.showToast({
    
    
              icon: 'none',
              title: '上传失败',
            })
            console.log(tempFilePaths[0])
          }
        })
      }
    })

  },

经过与后台数据库实测,可以上传更新用户的头像。
主要涉及的API有wx.showActionSheet,wx.chooseImage,wx.uploadFile,分别是弹出选择菜单,选择图像,上传文件。注意函数之间的调用关系。

猜你喜欢

转载自blog.csdn.net/qq_43263320/article/details/111588259