解决前端处理后端返回的二进制流文件
请使用axios来发送请求
ajax配置responseType会报错
Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer').
使用axios一定要配置*responseType: ‘arraybuffer’*来接收二进制数据,这里我需要接收的是PDF文件
完整代码请看下面
axios.get(filePath,{
responseType: 'arraybuffer',
headers: {
'x-debugger' : true,
},
}).then(res=>{
debugger
const blob = new Blob([res.data], {type: "application/pdf;chartset=UTF-8"});
// const fileName = "文件名.pdf";
if ("download" in document.createElement("a")) {
// // 非IE下载
const elink = document.createElement("a");
// elink.download = fileName;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
console.log(blob, elink.href, "href", elink);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
} else {
// IE10+下载
navigator.msSaveBlob(blob, fileName);
}
})