Vue前端导出文件:
后端传回前端的是文件流
//导出TXT
exportTxt:function(row){
let params={
"token":sessionStorage.getItem('token'),
"data":{
"busineeserId":row.businesserId,
"parkCode":row.parkCode,
"operateMode":row.operateMode
}
}
this.$api.ParingRegisterManage.downloadPrintFile(params).then((res)=>{
let blob = new Blob([res.data], { type: 'multipart/form-data' });
//解码前的文件名
let fileName1=res.headers['content-disposition'].split("=")[1].split(".")[0].replace('"',"");
//解码
let fileName=decodeURIComponent(fileName1);
var filename = fileName+".txt";
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
var body = document.getElementsByTagName('body')[0];
body.appendChild(a);
a.click();
body.removeChild(a);
window.URL.revokeObjectURL(url);
})
},
前端上传文件
效果图:
<el-upload class="upload-demo" action="auto" :http-request='submitUpload' ref="upload" :limit="1"
:on-remove="handleRemove" :before-upload="beforeUpload" :file-list="fileList">
<el-button size="mini" type="success" :disabled="uploadBtn">上传<i class="el-icon-upload el-icon--right"></i></el-button>
</el-upload>
所用到的部分参数:
http-request: 覆盖默认的上传行为,可以自定义上传的实现;
limit: 最大允许上传个数;
on-remove: 文件列表移除文件时的钩子;
before-upload: 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传;
file-list: 上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}];
其余参数可参考:https://element.eleme.cn/#/zh-CN/component/upload
//上传前校验
beforeUpload:function(file){
let _self=this;
let fileName=file.name.split(".");
let len=fileName.length;
let xls=fileName[len-1]==='xls';
let xlsx=fileName[len-1]==='xlsx';
if(!xls&&!xlsx){
_self.$message({message:'文件格式目前仅支持.xls或者.xlsx',type:'warning'});
return false;
}
},
//移除文件
handleRemove(file, fileList) {
this.fileList=[];
this.uploadBtn=false;
},
//自定义的上传方法
submitUpload: function(content) {
let var_this = this;
var_this.uploadFile=content.file;
var_this.uploadBtn=true;
},
在自定义的上传方法submitUpload()时,我并没有将文件上传,而是在点击“导入”按钮时,我才真正的将文件上传。
代码如下:
//导入EXCEL
excelImport:function(){
if(this.uploadFile==''){
this.$message({message:'请选择上传文件!',type:'warning'});
return;
}
this.loading=true;
let formData = new FormData;
formData.append('file',this.uploadFile);
formData.append('token',sessionStorage.getItem('token'));
formData.append('businesserId',this.businesserId);
formData.append('subsystemCode',this.subsystemCode);
this.$api.ParingRegisterManage.excelImport(formData).then((res)=>{
this.loading=false;
if(res.result==0){
this.$message({message:"成功导入行数:"+res.data.successNum+",失败导入行数:"+res.data.errorNum+","+res.data.msg,type:'success'})
this.fileList=[];
this.uploadFile='';
this.importDialogVisible=false;
}else if(res.result==1){
this.$message({message:res.msg,type:'error'})
}else if(res.result==2){//token失效
this.$router.push('/login')
}
})
},