html:
<el-upload
ref="uploadRef"
class="upload-demo"
multiple
action
:file-list="form.rechargeVoucher"
list-type="text"
:before-upload="beforeUpload"
:http-request="uploadFile"
:on-remove="removeFile"
>
<el-button size="small" icon="el-icon-s-goods">选择附件</el-button>
<div slot="tip" class="el-upload__tip">支持格式:.rar .zip .doc .docx .pdf ,单个文件不能超过20MB</div>
</el-upload>
data() {
return {
// --
form: {
rechargeVoucher: [],
},
},
methods: {
removeFile(file, fileList) {
this.form.rechargeVoucher = fileList;
},
beforeUpload(file) {
const fileTypes = this.getFileTypes();
const isTrueType = fileTypes.has(file.type);
const isLt2M = file.size / 1024 / 1024 < 20;
if (!isLt2M) {
this.$message.error("上传文件大小不能超过 20MB!");
}
if (!isTrueType) {
this.$message.error("上传文件格式不支持");
}
return isLt2M && isTrueType;
},
uploadFile(fileObj) {
const file = fileObj.file;
const name = file.name;
let formData = new FormData();
formData.set("file", fileObj.file);
// api请求后台接口,将formData发送给后台,后台返回图片url:res
api.witnessUploadOssLicense({formData}).then(res => {
this.form.rechargeVoucher.push({name: name, url: res, status: 'success'});
this.$refs['form'].validateField('rechargeVoucher');
this.form.rechargeVoucher = this.form.rechargeVoucher.filter(x => x.status === 'success');
})
},
getFileTypes() {
let fileTypes = new Set();
fileTypes.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
fileTypes.add("application/msword");
fileTypes.add("application/x-rar-compressed");
fileTypes.add("application/zip");
fileTypes.add("application/pdf");
return fileTypes;
}
}