需要实现文件下载的功能,有如下两种情况:
1.如果符合条件,返回文件流
2.如果不符合条件,则后端返回JSON,附上失败的msg,前端需要将msg的内容展示给用户
uploadSectionFile(params){
let fileName = params.file.name
let fileType = ''
if (fileName) {
fileType = fileName.split('.').pop()
}
const isLt1GB = params.file.size / 1024 / 1024 < 1024
if (['xls'].indexOf(fileType.toLowerCase()) === -1) {
this.$message.error('上传文件只能是 xls 格式!')
return
}
if (!isLt1GB) {
this.$message.error('上传文件大小不能超过 1GB!')
return
}
const form = new FormData();
form.append("file", params.file);
this.loading = true
this.$http({
url: '',
type: 'post',
params: form,
responseType: "blob",
forced:true,
All:true,
}).then(res=>{
this.loading = false
if(res.data.type=='application/json'){
const reader = new FileReader()
reader.onload = ()=> {
let resp = JSON.parse(reader.result)
if(resp){
if(resp.httpCode!=200){
this.$message.error(resp.msg ? resp.msg : '上传失败')
return
}
}
}
reader.readAsText(res.data)
}else{
this.$tools.daochuDownload(res)
}
}).catch(e=>{
this.loading = false
})
}
封装下载文件方法地址>>>>>