使用 axios 请求 api 下载导出一个文件时,接口返回值可能会出现两种情况:
1、文件流
2、json 对象
responseType 值的类型
值 | 数据类型 |
'' | DOMString(默认类型) |
arraybuffer | ArrayBuffer 对象 |
blob | Blob 对象 |
document | Documnet 对象 |
json | JavaScript object, parsed from a JSON string returned by the server |
text | DOMString |
实例
返回值不同情况的处理方式,举例如下:
1.请求设置为 responseType: ‘arraybuffer’
请求成功时,后端返回文件流,正常导出文件;
请求失败时,后端返回 json 对象,如:{“Status”:“false”,“StatusCode”:“500”,“Result”:“操作失败”},也被转成了 arraybuffer
此时请求成功和失败返回的 http 状态码都是 200
解决方案: 将已转为 arraybuffer 类型的数据转回 Json 对象,然后进行判断
代码如下
async downloadFile (file) {
let res = await this.$axios.post(this.API.order.tradeImpExcle, { responseType: "arraybuffer" });
if (!res) return;
try {
//如果JSON.parse(enc.decode(new Uint8Array(res.data)))不报错,说明后台返回的是json对象,则弹框提示
//如果JSON.parse(enc.decode(new Uint8Array(res.data)))报错,说明返回的是文件流,进入catch,下载文件
let enc = new TextDecoder('utf-8')
res = JSON.parse(enc.decode(new Uint8Array(res.data))) //转化成json对象
if (res.Status == "true") {
this.refresh()
this.$message.success(res.Msg)
} else {
this.$message.error(res.Result)
}
} catch (err) {
const content = res.data;
const blob = new Blob([content]);
let url = window.URL.createObjectURL(blob);
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute(
"download",
res.headers["content-disposition"].split("=")[1]
);
document.body.appendChild(link);
link.click();
}
}
2.请求设置为 responseType: ‘blob’
解决方案: 将已转为 blob 类型的数据转回 Json 对象,然后进行判断
代码如下
async downloadFile (file) {
let formData = new FormData();
formData.append("allTradesExcelFile", file);
let res = await this.$axios.post(this.API.order.tradeImpExcle, formData, { responseType: "blob" });
if (!res) return;
let r = new FileReader()
let _this = this
r.onload = function () {
try {
// 如果JSON.parse(this.result)不报错,说明this.result是json对象,则弹框提示
// 如果JSON.parse(this.result)报错,说明返回的是文件流,进入catch,下载文件
res = JSON.parse(this.result)
if (res.Status == "true") {
_this.refresh()
_this.$message.success(res.Msg)
} else {
_this.$message.error(res.Result)
}
} catch (err) {
const content = res.data;
const blob = new Blob([content]);
let url = window.URL.createObjectURL(blob);
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute(
"download",
res.headers["content-disposition"].split("=")[1]
);
document.body.appendChild(link);
link.click();
}
}
r.readAsText(res.data) // FileReader的API
}
转自:https://blog.youkuaiyun.com/lhz_333/article/details/102495755
使用download.js下载
import axios from 'axios';
import download from 'downloadjs';
import { format } from 'date-fns'; //格式化时间模块
axios.post('http://www.lihefei.com', {
name: 'lihefei'
}, {
responseType: 'blob' //设置接口响应返回的数据流类型
}).then(response => {
let blob = resolve.data; //文件数据流
let timestamp = format(new Date(), 'yyyyMMddHHmmss') + new Date().getMilliseconds(); //当前年月日时分秒毫秒时间戳,例:2020070818090274
let fileName = timestamp + '.xls'; //文件名,例:2020070818090274.xls
let mimeType = 'application/vnd.ms-excel'; //xls格式文件对应的类型为:application/vnd.ms-excel
download(blob, fileName, mimeType); //下载文件
}).catch(function (err) {
console.log(err);
});
文件格式与类型对照表:https://lihefei.blog.youkuaiyun.com/article/details/101445668
其他方式
axios.post('http://www.lihefei.com', {
name: 'lihefei'
}).then(response => {
const blob = response;
const reader = new FileReader();
reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情href
reader.onload = function (e) {
// 转换完成,创建一个a标签用于下载
const a = document.createElement("a");
a.download = "test.xls";
a.href = e.target.result;
const body = document.querySelector('body');
body.append(a); // 修复firefox中无法触发click
a.click(); //触发点击下载
body.removeChild(a);
};
}).catch(function (err) {
console.log(err);
});