Vant Uploader Upload one or more pictures component
- 2021-11-24 00:27:15
- OfStack
This article example for everyone to share Vant Uploader to upload one or more pictures component, for your reference, the specific content is as follows
html Part
<template>
<div class="contWrap">
<van-uploader
v-model="fileList"
:multiple="true"
:before-read="beforeRead"
:after-read="afterRead"
:before-delete="delUploadImg"
upload-icon="plus"
>
<!-- Note: This is a custom upload style -->
<!-- <p>
<van-icon
name="plus"
color="#07c160"
size=".5rem"
/>
Upload photos
</p> -->
</van-uploader>
</div>
</template>
js Part
<script>
import axios from "axios";
export default {
name: "uploadImages",
data() {
return {
fileList: [],
uploadUrl: "/api/upload/fileUpload",
headers: {
token: this.$store.state.account.token,
},
};
},
methods: {
// Returns a Boolean value
beforeRead(file) {
if (file instanceof Array) {
// Determine whether it is an array
file.forEach((v) => {
this.checkFile(v);
});
} else {
this.checkFile(file);
}
return true;
},
// Picture type checking
checkFile(file) {
const format = ["jpg", "png", "jpeg"];
const index = file.name.lastIndexOf(".");
const finalName = file.name.substr(index + 1);
if (!format.includes(finalName.toLowerCase())) {
Toast(" Please upload " + format.join(",") + " Format picture ");
return false;
}
},
afterRead(file) {
// At this time, you can upload files to the server by yourself
if (file instanceof Array) {
file.map((v) => {
v.status = "uploading";
v.message = " Upload in ...";
this.uploadImg(v);
});
} else {
file.status = "uploading";
file.message = " Upload in ...";
this.uploadImg(file);
}
},
// Upload
uploadImg(file) {
const formData = new FormData();
formData.append("file", file.file);
axios
.post(this.uploadUrl, formData, {
headers: this.headers,
})
.then((res) => {
if (res.data) {
if (file instanceof Array) {
// Determine whether it is an array
file.map((v, i) => {
v.status = "success";
v.message = "";
v.url = res.data[i];
});
} else {
file.status = "success";
file.message = "";
file.url = res.data.uploadUrl;
}
}
})
.catch((err) => {
this.$notify({
type: "warning",
message: " Upload failed ",
});
});
},
// Delete
delUploadImg(item) {
this.fileList = this.fileList.filter((v) => v.url != item.url);
}
},
};
</script>