前端get、post请求接收后端返回的二进制文件流下载到本地
前端get、post请求接收后端返回的二进制文件流下载到本地
请求接口时一定要加上 responseType: 'blob’或responseType: ‘arraybuffer’,且responseType与headers是同级不要写在里面
axios({
method: "post",
url: "xxxx",
headers: {},
responseType: "arraybuffer",
});
下载方法
export const downloadAsExcel = (data, name) => {
// data是二进制流,通过new Blob方法转化为Blob,type是下载文件格式,本方法以excel为例
// name是你想下载的文件名
const url = window.URL.createObjectURL(
new Blob([data],
{ type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" })
);
//如果后端返回的是Blob,则不需要用上面的方法new Blob直接用data
//const url = window.URL.createObjectURL(data);
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", `${name}` || "template.xls");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
最后为了您和他人的健康,开发时请多写注释