最近做h5开发遇到的问题:项目用到的ui库为有赞的vant。在操作uploader组件时遇到了一些小坑,分享一下。
需求:用户头像点击上传和上传后刷新
html部分:
<van-uploader :afterRead="afterRead" class="fr">
<van-image
round
width="2rem"
height="2rem"
:src="userInfo.avatarUrl"
/>
</van-uploader>
使用van-uploader组件、读取用户选取的图片后触发afterRead事件。
注意:header中Content-Type要改为multipart/form-data,用Jason格式传不了文件~
(element用多了,都是自动发的请求,把这些细节忘了 ^_^……)
afterRead(file) {
console.log(file);
this.headImg = file.file;
let formData = new FormData();
formData.append("file", file.file);
axios
.post("common/upload", formData, {
headers: {
//添加请求头
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
if (res.data.code == 200) {
// this.headImg = null;
this.updateDesc({
customId: localStorage["customId"],
avatarFileId: res.data.data.fileId,
});
}
});
},