在表单中实现文件上传功能。
1.通过element-ui中的el-upload组件,调用后台接口上传文件,返回文件名和存储地址。
2.监听fileList变化,有变动时,更新表单中文件名称和文件url属性值。
el-upload组件
<el-form-item label="上传文件" required>
<el-upload
class="upload-file-uploader"
:headers="headers"
:action="uploadFileUrl"
:limit="limit"
:on-exceed="handleExceed"
:before-upload="handleBeforeUpload"
:on-error="handleUploadError"
:on-success="handleUploadSuccess"
:on-remove="handleRemove"
:file-list="fileList"
>
<!-- 上传按钮 -->
<el-button size="mini" type="primary">选取文件</el-button>
<!-- 上传提示 -->
<div class="el-upload__tip" slot="tip">请上传
<template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
<template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>的文件
</div>
</el-upload>
</el-form-item>
参数定义 :文件大小、类型、个数、上传地址等
headers: {
Authorization: "Bearer " + getToken(),
},
uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload",
limit: 1,
fileSize: 5,
fileType: ['txt'],
fileList: [],
组件响应方法
// 上传前校检格式和大小
handleBeforeUpload(file) {
// 校检文件类型
if (this.fileType) {
const fileName = file.name.split('.');
const fileExt = fileName[fileName.length - 1];
const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
if (!isTypeOk) {
this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
return false;
}
}
// 校检文件大小
if (this.fileSize) {
const isLt = file.size / 1024 / 1024 < this.fileSize;
if (!isLt) {
this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
return false;
}
}
this.$modal.loading("正在上传文件,请稍候...");
return true;
},
// 文件个数超出
handleExceed() {
this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
},
// 上传失败
handleUploadError(err) {
this.$modal.msgError("上传文件失败,请重试");
this.$modal.closeLoading()
},
// 上传成功回调
handleUploadSuccess(res, file) {
if (res.code === 200) {
//将响应结果存入到fileList中
this.fileList.push({ name: res.originalFilename, url: res.url });
this.$modal.closeLoading();
} else {
this.handleRemove(file);
this.$modal.closeLoading();
this.$modal.msgError(res.msg);
}
},
// 删除文件
handleRemove(file) {
this.fileList.splice(this.fileList.indexOf(file), 1);
},
监听fileList的变动,给表单属性赋值。
watch: {
fileList: {
handler(val) {
if(val.length > 0){
this.form.wjmc = val[0].name;
this.form.wjurl = val[0].url;
}else {
this.form.wjmc = "";
this.form.wjurl = "";
}
},
immediate: true,
deep: true
}
}
注意:
1.表单重置清空时,将fileList清空;
this.fileList = [];
this.resetForm("form");
2.表单提交时,校验fileList是否为空。
if(this.fileList && this.fileList.length === 0){
this.$modal.msgError("请上传文件");
}