代码:
<el-upload
:auto-upload="false"
multiple
class="upload-demo"
action="#"
:on-change="uploadChange"
:before-upload="handleBeforeUpload"
:before-remove="beforeRemove"
:on-remove="upLoadRemove"
:on-preview="downLoadFile"
:file-list="fileList"
>
<el-button size="small" icon="el-icon-plus" slot="trigger"
>选取文件</el-button
>
<el-button
style="margin-left: 10px"
size="small"
icon="el-icon-upload"
type="success"
@click="submitUpload"
:disabled="fileList.length <= 0"
>上传到服务器</el-button
>
<div class="el-upload__tip" slot="tip">仅限doc和docx文件</div>
</el-upload>
// 多文件上传
fileUpload() {
this.fileList = [];
this.filedialogVisible = true;
},
// 上传前
handleBeforeUpload(file) {
console.log(file);
// 校验
let legalName = ["doc", "docx"];
// 拿到后缀名
let name = file.name.substring(
file.name.lastIndexOf(".") + 1,
file.name.length
);
if (legalName.includes(name)) {
// console.log(legalName.includes(name));
} else {
this.$message.info("文件格式不对,仅限doc和docx");
return false;
}
},
// 拖拽上传
beforeRemove(file, fileList) {
this.fileList = fileList;
// return this.$confirm(`确定移除 ${file.name}?`);
},
// 移除附件
upLoadRemove(file, fileList) {
let tempFileList = [];
for (var index = 0; index < this.fileList.length; index++) {
if (this.fileList[index].name !== file.name) {
tempFileList.push(this.fileList[index]);
}
}
this.fileList = tempFileList;
},
// 监控上传文件列l表
uploadChange(file, fileList) {
let existFile = fileList
.slice(0, fileList.length - 1)
.find((f) => f.name === file.name);
if (existFile) {
this.$message.error("当前文件已经存在!");
fileList.pop();
}
this.fileList = fileList;
// 校验
let legalName = ["doc", "docx"];
// 拿到后缀名
let name = file.name.substring(
file.name.lastIndexOf(".") + 1,
file.name.length
);
if (legalName.includes(name)) {
console.log(legalName.includes(name));
} else {
this.$message.info("文件格式不对,仅限doc和docx");
return false;
}
},
// 上传到服务器 formidable接收
async submitUpload() {
let formData = new FormData();
this.fileList.forEach((item) => {
formData.append("files", item.raw);
});
formData.append("parentId", this.allId);
// append追加后console.log后仍为空,需要用formData.get("键")的方法获取值
const res = await fileUpload(formData);
console.log(res);
if (res.status != 200) {
return this.$message.error("上传失败");
}
this.$message.success("上传成功");
this.fileBox(this.allId);
this.filedialogVisible = false;
},
// 点击文件进行下载
downLoadFile(file) {
var a = document.createElement("a");
var event = new MouseEvent("click");
a.download = file.name;
a.href = file.url;
a.dispatchEvent(event);
},
// :on-exceed="handleExceed"
// 选取文件超过数量提示
// handleExceed(files, fileList) {
// this.$message.warning(`当前限制选择 5 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
// },