vant上传图片并接收返回值
bug方案
- 在afterRead之后上传整个数组的话,会导致前面图片重复上传 (适用于只上传一张照片)
<van-uploader
v-model="fileList2"
:after-read="afterRead2"
:max-count="1"
/>
afterRead2() {
this.fileList2.forEach((item) => {
this.$set(item, "status", "uploading");
this.$set(item, "message", "上传中");
this.upload(item).then((res) => {
this.$set(item, "img", res.url);
this.$set(item, "status", "success");
});
});
}
- 只上传数组的最后一项,但是如果是多选就不能全部上传 (适用于单张上传)
<van-uploader
v-model="fileList1"
:after-read="afterRead1"
:max-count="3"
/>
afterRead2() {
let item = this.fileList2[this.fileList2.length - 1];
this.$set(item, "status", "uploading");
this.$set(item, "message", "上传中");
this.upload(item).then((res) => {
this.$set(item, "img", res.url);
this.$set(item, "status", "success");
});
}
推荐方案
- 根据fileList1中每一项item.status的状态如果不是success就说明没有上传成功过,就上传 (适用于多选上传)
<van-uploader
v-model="fileList1"
:after-read="afterRead1"
multiple
:max-count="3"
/>
afterRead1() {
this.fileList1.forEach((item) => {
if (item.status != "success") {
this.$set(item, "status", "uploading");
this.$set(item, "message", "上传中");
this.upload(item).then((res) => {
this.$set(item, "img", res.url);
this.$set(item, "status", "success");
}).catch(() => {
this.$set(item, "img", "");
this.$set(item, "status", "failed");
});
}
});
}
上传成功的回调处理
- fileList1 既能实时展示图片,又能实现预览效果 (url属性起作用)
- fileList1,里边的file属性就是可上传的的file文件
- 上传成功的回调里将返回的图片地址存入数组的新属性img 中,最后在上传的时候取出来
上传方法
upload(file) {
const forms = new FormData();
forms.append("file", file.file);
return this.$axios.post("/stage-api/dfs/customerUpload", forms, {
headers: {
"content-type": "multipart/form-data",
},
});
},
上传方法的封装方式
<van-form @submit="onSubmit">
<van-field name="uploader" label="文件上传">
<template #input>
<van-uploader
v-model="uploader"
:after-read="afterRead"
:max-count="3"
preview-size="2rem"
/>
</template>
</van-field>
<van-button round block type="info" native-type="submit">
提交
</van-button>
</van-form>
data() {
return {
uploader: []
};
},
methods: {
afterRead(file) {
file.status = "uploading";
file.message = "上传中...";
try {
const { data } = await upImage(file.file);
file.status = 'done';
file.url = data.url;
} catch (error) {
file.status = 'failed';
}
onSubmit(values) {
console.log("submit", values);
}
}
npm i lrz --save
import lrz from "lrz";
export const upImage = async file => {
const { formData } = await lrz(file);
return http.post('/common/uploadali', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
});
};