在微信中上传头像的时候他返回的是临时路径,但是后端需要的是文件对象,当时想了很多办法,但小程序的生态没有那么好,最后去看uniapp的文档,然后想到了一个方法实现,就是先下载然后上传就可以了
uniapp
// 头像
const onChooseAvatar = (e) => {
console.log(e, 'e---> 1');
const {
avatarUrl
} = e.detail
// this.setData({
// avatarUrl,
// })
console.log("获取到用户头像avatarUrl:" + avatarUrl)
// 头像图片
uni.getImageInfo({
src: avatarUrl,
success(res) {
console.log('download success');
const tempFilePath = res.tempFilePath
console.log("获取到用户头像tempFilePath:" + tempFilePath)
// 上传下载的图片
uni.uploadFile({
url: 'https://cipp.ecaray.com/file/upload',
filePath: tempFilePath,
name: 'file',
fileType: 'image',
header: {
'Authorization': `Bearer ${JSON.parse(uni.getStorageSync('ACCESS_TOKEN'))}`
},
formData: {
fileType: 'img',
bucket: 'cipp-road-park-img',
tags: '用户头像',
},
success(res) {
const data = JSON.parse(res.data)
console.log('upload success');
let {
fileAccessUri,
filePath
} = data.result
console.log("成功获取到用户头像存入数据库:", data.result);
console.log(listData,fileAccessUri + filePath);
listData.value.avatar = fileAccessUri + filePath
console.log(listData.value.avatar,'avatar');
},
fail(res) {
console.log('upload fail');
}
})
}
})
}
微信
// 头像
const onChooseAvatar = (e) => {
console.log(e, 'e---> 1');
const {
avatarUrl
} = e.detail
// this.setData({
// avatarUrl,
// })
console.log("获取到用户头像avatarUrl:" + avatarUrl)
// 下载头像图片
wx.downloadFile({
url: avatarUrl,
success(res) {
if (res.statusCode === 200) {
console.log('download success');
const tempFilePath = res.tempFilePath
console.log("获取到用户头像tempFilePath:" + tempFilePath)
// 上传下载的图片
wx.uploadFile({
url: 'https://cipp.ecaray.com/file/upload',
filePath: tempFilePath,
name: 'file',
fileType: 'image',
header: {
'Authorization': `Bearer ${JSON.parse(uni.getStorageSync('ACCESS_TOKEN'))}`
},
formData: {
fileType: 'img',
bucket: 'cipp-road-park-img',
tags: '用户头像',
},
success(res) {
const data = JSON.parse(res.data)
console.log('upload success');
let {
fileAccessUri,
filePath
} = data.result
console.log("成功获取到用户头像存入数据库:", data.result);
console.log(listData,fileAccessUri + filePath);
listData.value.avatar = fileAccessUri + filePath
console.log(listData.value.avatar,'avatar');
},
fail(res) {
console.log('upload fail');
}
})
}
}
})
}