axios上传文件并下载文件流
import { message } from "antd";
import axios from "axios";
//请求后端二进制流数据
export function binaryFileDownLoad(url, params, fileName) {
return new Promise((resolve, reject) => {
return axios.post(url, params,{ responseType: "blob" }).then((res) => {
if (res.status == 200) {
const { data } = res;
if (data.type === "application/json") {
const reader = new FileReader();
reader.readAsText(data, "utf-8");
reader.onload = () => {
const error = JSON.parse(reader.result);
if (error && error.code != 0) {
message.error({
content: error.msg ? error.msg : error.message ? error.message : "数据异常",
duration: 6,
});
}
reject(error);
};
} else {
if (!fileName) {
//想让浏览器访问到其他相应头,需要在后服务器上设置Access-Control-Expose-Headers。
//想要在这里访问到content-disposition中定义的文件名,需要在后端设置headers.add("Access-Control-Expose-Headers", "Content-Disposition");
let contentDisposition = res.headers["content-disposition"];
if (contentDisposition) {
fileName = window.decodeURI(res.headers["content-disposition"].split("=")[1], "UTF-8");
}
}
executeDownload(data, fileName);
resolve({ code: 0, data: res.data });
}
}
});
});
}
//创建二进制内容并下载
export function executeDownload(data, fileName) {
if (!data) {
return "";
}
// 构建文件【二进制内容】
const blob = new Blob([data]);
//非IE下载
if ("download" in document.createElement("a")) {
let url = window.URL.createObjectURL(blob);
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} else {
// IE10+下载
navigator.msSaveBlob(blob, fileName);
}
}