vue+ele中文件上传实现
<template>
<el-form label-width="140px" style="padding-top: 20px" v-if="active == 0" ref="form" :model="form" :rules="rules" > <el-form-item label="导入表格" prop="file" style="width: 450px"> <el-upload class="upload-demo" ref="upload" accept=".xlsx,.xls" :auto-upload="false" action="action" :http-request="uploadOk" :on-change="onChange" :on-exceed="onExceedUpload" :before-remove="removefile" :limit="1" :file-list="fileListAdd" v-model="form.file" > <el-button slot="trigger" size="small" type="primary" @click="clearCheck" >选取文件</el-button > <div slot="tip" class="el-upload__tip el-upload__tips"> 只支持上传一个文件</div > </el-upload> <div class="fileClass" :loading="loadings" @click="modeDownload" >模板.xlsx</div > </el-form-item>
<div style="text-align: center; margin-top: 50px">
<el-button
size="small"
type="primary"
:loading="loading"
@click="submit"
v-show="hide"
>
下一步
</el-button>
</div>
</el-form>
</template>
<script>
export default {
data() {
return {
form: {file: '' }, rules: { file: [ { required: true, message: '请选择文件上传', trigger: 'change' } ] }, fileListAdd: [], // 上传文件列表
}
}
}
methods: {
//文件与其他输入类型的字段一起提交上传
uploadOk(file) {
this.uploaddata = {
// fileName: file.file.name,
其他字段: this.form.其他字段,
其他字段1: this.form.其他字段1
};
let params = new FormData();
for (const key in this.uploaddata) {
params.append(key, this.uploaddata[key]);
}
params.append('file', file.file);
this.loading = true;
接口名称+(params)
.then((list) => {
this.$refs.upload.clearFiles();
this.fileListAdd = [];
this.loading = false;
this.active = 1;//进入第二步
})
.catch((e) => {
this.loading = false;
this.$message.error(e.message);
});
},
//导入的下一步
submit() {
this.$refs['form'].validate((valid) => {
if (valid) {
this.$refs.upload.submit();
} else {
return false;
}
});
},
//第一个上一步
preBack() {
this.active = 0;
this.fileListAdd.push(this.form.file);
},
//文件状态改变的函数
onChange(fileList) {
this.$set(this.form, 'file', fileList);
},
//文件超出个数限制时触发的函数
onExceedUpload() {
this.$alert(
'文件数量超出限制,若想重新上传,请先删除已选择的文件重新上传',
'上传结果',
{
dangerouslyUseHTMLString: true
}
);
},
removefile() {
this.$set(this.form, 'file', '');
},
clearCheck() {
this.$refs.form.clearValidate('file');
},
}
</script>