话不多说直接上代码,这里直接封装成一个组件,可以复用
- 点击上传的时候才会上传附件,可以fileVoList当作参数传给后端,是一个附件列表数组
<template>
<el-upload
class="upload-demo"
ref="upload"
multiple
action="/"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-change="fileLimit"
:file-list="accessoryList"
:http-request="submitAccessoryList"
:on-success="upSuccessAccessory"
:auto-upload="false"
>
<el-button slot="trigger" size="small" type="primary">请选择文件</el-button>
<el-button
style="margin-left: 10px"
size="small"
type="linear"
@click="submitUpload"
>上传</el-button
>
<el-button
style="margin-left: 10px"
size="small"
type="default"
@click="(e) => (accessoryList = [])"
>取消上传</el-button
>
<span style="color: red">(温馨提示:单个文件不超过5M)</span>
</el-upload>
</template>
<script>
import {
uploadAttachment } from "@/api";
export default {
props: {
action: {
type: String,
default: () => "/",
},
},
data() {
return {
accessoryList: [],
fileVoList: [],
callback: null
};
},
methods: {
handlePreview(file) {
console.log("file是:", file.name);
},
handleRemove(file) {
this.$message.warning(`已移除${
file.name}`);
const index = this.fileVoList.findIndex(
(item) => item.fileName == file.name
);
this.fileVoList.splice(index, 1);
this.$emit("makeSure", this.fileVoList);
},
async submitAccessoryList(param) {
try {
let formData = new FormData();
formData.append("file", param.file);
const res = await uploadAttachment(formData);
this.fileVoList.push(res.data);
if (this.fileVoList.length === this.accessoryList.length && typeof this.callback === 'function') {
this.callback();
}
} catch (e) {
console.log("上传失败", e);
}
},
submitUpload() {
this.test().then((res) => {
if (res.code == 200) {
this.callback = () => {
this.fileVoList = this.fileVoList.map((item) => {
return {
fileName: item.name,
fileSize: item.size,
fileUrl: item.url,
id: item.id,
};
});
this.$emit("makeSure", this.fileVoList);
}
}
});
},
test() {
return new Promise((res, rej) => {
if (this.accessoryList.length > 0) {
this.$refs.upload.submit();
res({
code: 200 });
} else {
this.$message.error('请选择上传文件')
rej({
code: 500 });
}
});
},
fileLimit(file, fileList) {
const extension = file.name.substring(file.name.lastIndexOf('.') + 1);
const size = file.size / 1024 / 1024;
if(extension !== 'zip') {
this.$message.warning('只能传后缀名为.zip的压缩文件')
return
}
if (size > 5) {
this.$message.warning("文件大小不得超过5M");
return;
}
this.accessoryList = fileList;
},
upSuccessAccessory() {
this.$message.success("附件上传成功");
},
},
};
</script>
<style>
.el-upload-list {
width: 500px;
}
</style>