带excell后缀校验,效果如下
<!-- Excel上传 -->
<el-dialog title="文件上传"
:visible.sync="excelVisible" width="40%" center>
<el-upload style="text-align:center"
:show-file-list="false"
:on-error="handleError"
:on-success="handleSuccess"
:before-upload="handleBeforeUpload"
class="upload-demo"
drag
:action="upUrl"
multiple
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">
仅限xls和xlsx文件
</div>
</el-upload>
<span slot="footer" class="dialog-footer">
<el-button style="margin-right:20px" size="mini" @click="excelVisible = false">取 消</el-button>
<el-link target="_blank" :href="downUrl">
<el-button size="mini" type="success"
>下载模板</el-button >
</el-link>
</span>
</el-dialog>
data
upUrl : url.upUrl,
downUrl : url.downUrl,
methods
handleBeforeUpload(file){
// 校验
let legalName = ['xlsx','xls']
// 拿到后缀名
let name = file.name.substring(file.name.lastIndexOf('.') + 1,file.name.length)
if(legalName.includes(name)){
console.log(legalName.includes(name));
}else{
this.$message.info('文件格式不对,仅限xls和xlsx')
return false
}
},
handleError(err){
// console.log(err);
this.$message.info(err.data)
},
handleSuccess(response){
// console.log(response);
if(response.isSuccess){
this.$message.success(response.error)
this.getListByParam()
return
}
this.$message.info(response.error)
},
如果上传后端返回文件流,但elementUi自带的上传不能设置responseType: “arraybuffer”,只能自己写;
uploadSectionFile(params){
let form = new FormData()
form.append('file',params.file)
this.axios.post(`/busFbx/getGoodsCategory`,form,{responseType: "arraybuffer"})
.then((res) => {
let a = document.createElement("a");
let blob = new Blob([res.data]);
let objectUrl = URL.createObjectURL(blob);
a.setAttribute("href", objectUrl);
a.setAttribute("download", "分类模板.xls");
a.click();
// console.log(objectUrl);
URL.revokeObjectURL(objectUrl); // 释放内存
}) .catch((res) => {
console.log(res);
});
},