Wechat applet about avatar upload and related APIs (showActionSheet, chooseImage and uploadFile)
Recently participated in the development of a WeChat applet, and there is a need for uploading avatars. After the implementation, I want to write a blog record, and hope to help friends in need.
Effect preview
Click on the area, you can pop up a menu to select
js code
changeAvatarSheet function
// 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 function
// 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])
}
})
}
})
},
After actual testing with the background database, you can upload and update the user's avatar.
The main APIs involved are wx.showActionSheet, wx.chooseImage, and wx.uploadFile, which are pop-up selection menus, select images, and upload files, respectively. Pay attention to the calling relationship between functions.