小程序項目中遇到需要更換用戶頭像的需求,這里記錄下,相關邏輯代碼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
})
}
})
}
})
},