相关代码
基本原理 根据返回的blob数据,利用 window.URL.createObjectURL生成url,通过 a 标签下载
const downloadFileByURL = async (url, filename) => {
const { data } = await axios({
method: 'get',
url: BASE_URL + url,
responseType: 'blob',
withCredentials: true,
headers: { 'Content-Type': 'application/json;charset=UTF-8' },
});
const blob = new Blob([data], { type: 'application/octet-stream' });
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.style.display = 'none';
link.href = downloadUrl;
link.setAttribute('download', filename);
// Safari thinks _blank anchor are pop ups. We only want to set _blank
// target if the browser does not support the HTML5 download attribute.
// This allows you to download files in desktop safari if pop up blocking
// is enabled.
if (typeof link.download === 'undefined') {
link.setAttribute('target', '_blank');
}
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(downloadUrl);
};