HTML结构如下:
<el-dialog title="导入" :visible.sync="dialogFormVisible" width="35%">
<el-form ref="fileForm" label-width="100px">
<el-form-item label="选择文件">
<el-upload
class="upload-demo"
ref="upload"
accept=".xlsx, .xlsm, .xls" //接受上传的文件类型
:auto-upload="false" //是否在选取文件后立即进行上传,默认值为true,改为false
action="#"
:limit="1" //最大允许上传个数
:file-list="fileList" // 上传的文件列表
:on-change="handleChange" //文件状态改变时调用,添加文件、上传成功和失败都会调用
:on-exceed="handleExceed" //文件超出个数限制时的钩子
:on-remove="handleRemove"> //文件列表移除文件时的钩子
<el-button size="small" style="width: 400px; text-align: right">
<i class="fa fa-folder-open-o"></i>
</el-button>
</el-upload>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="handleImportExcel" :disabled="uploading"
>确定导入</el-button>
<el-button @click="cancle">取消</el-button>
</div>
</el-dialog>
data如下:
export default {
data(){
return{
dialogFormVisible:false,
fileList:[], //文件列表
file:{},
uploading:true, //默认置灰确定导入按钮
}
}
}
methods如下:
//文件状态改变触发
handleChange(file) { //(file,fileList)参数
this.uploading = false;
this.file = file;
},
//文件超出个数限制
handleExceed() {
this.$message.warning("仅允许上传一个文件!");
},
//移除文件
handleRemove() {
this.uploading = true;
},
//取消
cancle() {
this.file = {};
this.fileList = [];
this.dialogFormVisible = false;
this.uploading = true;
},
//导入excel
handleImportExcel(){
if (!this.file.size) {
this.$message.warning("请选择上传的文件");
return;
}
this.uploading = true;
let formData = new FormData();
formData.append("file", this.file.raw);
post_prd_info_list(formData).then(res=>{ //调用接口
this.uploading = false;
if(res.code === "0"){
this.$message.success(res.msg)
}else{
this.$message.error(res.msg)
}
}).catch(err=>{
this.$message.error(err)
})
}//