// 选择头像
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,这里两种都允许
sourceType: ['album', 'camera', 'poster'], // 可以指定来源是相册、相机还是临时文件,这里三种都允许
success: (res) => {
const {errMsg,tempFilePaths,tempFiles}=res
if(errMsg!='chooseImage:ok'){
uni.showToast({
title: '上传失败',
icon: 'none'
})
return
}
// 进行上传图片
uni.uploadFile({
url: `${baseurl}/file/upload`, // 后端用于处理图片并返回图片地址的接口
method: 'POST', // 请求方法,根据后端接口要求选择GET或POST
header: {
"Content-Type": "multipart/form-data" , // formdata提交格式
},
filePath: tempFilePaths[0],
name: 'file', // 后端服务器接收上传文件的字段名,默认为'file'
formData: { // 其他的formdata参数
fileType: '2',
uid: '10001',
fileContainerName: 'default'
},
success: (res) => {
const {code,data:{name,url}} = JSON.parse(res.data); // 返回的是字符串,需要转成对象格式
if(code!=0){
uni.showToast({
title: '上传失败',
icon: 'none'
})
return
}
// 进行更新仓库
consumerStore.userInfo.avatar = url; // 将图片地址保存到用户信息中
},
fail: () => {
uni.showToast({
title: '上传失败',
icon: 'none'
})
}
});
}
});
Uniapp选择和上传头像
最新推荐文章于 2025-06-19 17:40:30 发布