一、需求
- 实现
.xls
与.txt
文件的上传功能,并添加表单必传校验
二、技术栈
- 前端框架:vue2
- 前端UI框架:Ant Design of Vue(v1.7.8)
三、代码
上传 .xls
文件
<template>
<a-modal
:title="title"
ok-text="确认"
cancel-text="取消"
:visible="visible"
:maskClosable="false"
destroyOnClose
@ok="save"
@cancel="reset"
>
<a-form-model :model="form" ref="ruleForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
<a-form-model-item ref="name" label="Activity name" prop="name">
<a-input v-model="form.name" />
</a-form-model-item>
<a-form-model-item label="文件" prop="file">
<a-upload
:file-list="fileList"
:remove="handleRemove"
:before-upload="beforeUpload"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
>
<a-button> <a-icon type="upload" /> 选择文件 </a-button>
<a-badge color="red" text="请选择.xls文件" style="margin-left: 10px" />
</a-upload>
</a-form-model-item>
</a-form-model>
</a-modal>
</template>
<script>
export default {
data() {
return {
labelCol: {
span: 6 },
wrapperCol: {
span: 16 },
visible: false,
title: '文件导入',
form: {
},
// 校验规则
rules: {
file: [
{
required: true,
trigger: 'change',
validator: this.uploadFileChange,
},
],
},
// 已经上传的文件列表
fileList: [],
};
},
methods: {
// 上传文件改变时的状态
handleChange(info) {
if (info.file.status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (info.file.status === 'done') {
this.$message.success(`${
info.file.name} 上传成功`);
} else if (info.file.status === 'error') {
this.$message.error(`${
info.file.name} 上传失败`);
}
},
// 关闭
reset() {
this.fileList = [];
this.visible = false;
},
// 确认
save() {
this.$refs.ruleForm.validate((valid) => {
if (valid) {
const {
fileList } = this;
const formData = new FormData();
fileList.forEach((file) => {
formData.append('file', file);
});
// 上传文件接口请求,一般将文件内容放在body里面
// api.xxx(formData).then((res) => {});
this.reset();
} else {
return false;
}
});
},
// 自定义上传附件校验
uploadFileChange(rule, value, callback) {
if (this.fileList.length === 0) {
return callback(new Error('请选择需要上传的文件'));
} else {
return true;
}
},
handleRemove(file) {
const index = this.fileList.indexOf(file);
const newFileList = this.fileList.slice();
newFileList.splice(index, 1);
this.fileList = newFileList;
},
beforeUpload(file) {
this.fileList = [...this.fileList, file];
return false;
},
},
};
</script>
<style lang='less' scoped>
/deep/ .ant-badge-status-text {
color: red;
}
</style>
备注:上传 txt
文件时将 <a-upload>
的 accept
修改为 text/plain
即可
四、效果