首发于CSDN:JavaScript Axios 或 Base64 客户端下载文件_kxh166的博客-CSDN博客 属于原创文章
本文章的代码在经过查阅资料并测试完成 可直接使用
客户端下载文件
function downloadFile(blob, fileName) {
let isDownload = false;
try {
// 非IE下载
if ("download" in document.createElement("a")) {
let link = document.createElement("a");
let URL = window.URL || window.webkitURL;
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.style.display = "none";
document.body.appendChild(link);
link.click();
// 下载完成 移除元素 释放blob对象
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
} else {
// IE10+下载
window.navigator.msSaveBlob(blob, fileName);
}
isDownload = true;
// eslint-disable-next-line no-empty
} catch (error) {}
return isDownload;
}
请求文件
安装引入 Axios 后,使用 axios(config) 自定义配置进行请求
config 常用选项:url method params data responseType headers
import axios from "axios";
function requestFile(config) {
let axiosConfig = Object.assign(
{
// 响应类型默认使用 blob
responseType: config.responseType || "blob"
},
config
);
return axios(axiosConfig);
}
Base64转换文件
function base64ToBlob(base64) {
const arr = base64.split(",");
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
通过 Axios 下载文件
async function download(config, fileName) {
let isDownload = false;
await requestFile(config).then(resp => {
let { data } = resp;
if (!data) {
return false;
}
// responseType 设置为 blob,返回的 data 的类型为 Blob
// const blob = new Blob([data], { type: contentType });
const contentDisposition = resp.headers["content-disposition"];
if (contentDisposition) {
fileName = window.decodeURI(
resp.headers["content-disposition"].split("=")[1]
);
}
isDownload = downloadFile(data, fileName);
});
return isDownload;
}
返回 Promise
通过 Base64 下载文件
function downloadByBase64(base64, fileName) {
let blob = base64ToBlob(base64);
return downloadFile(blob, fileName);
}