问题描述
在项目中使用a标签下载很方便,但是遇到权限等问题的时候,就需要我们对下载的这个包进行封装,那么我们可以使用axios创建下载链接
附上自定义导入的js函数:
const export_excel = () => {
let handle_search = JSON.parse(JSON.stringify(search_info.value))
Object.keys(handle_search).forEach((key) => {
if (key == 'showField') {
delete handle_search[key]
}
if (handle_search[key] == '' || handle_search[key] == null) {
delete handle_search[key]
}
})
let subURL = `/api/exportByExcel?pageId=${props.pageId}`
Object.keys(handle_search).forEach((key) => {
subURL += '&' + key + '=' + handle_search[key]
})
location.href = baseURL + subURL;
}
解决方案:
- 使用axios发起一个GET请求获取要下载的文件的二进制数据。
- 将获取到的二进制数据转换为Blob对象。
- 创建一个URL对象,并将Blob对象传入URL.createObjectURL方法中生成一个可供下载的链接地址。
const axios = require('axios');
axios({
url: 'http://example.com/file.pdf',
method: 'GET',
// 关键
responseType: 'blob',
}).then((res) => {
const url = window.URL.createObjectURL(new Blob([res.data]));
// 方法1
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
// 方法2
// window.location.href = url;
});
a标签实际上不会在浏览器中显示出来。它是一个虚拟元素,只用于触发文件下载。
使用 window.location.href 触发下载的方法也是可行的,但它可能会在一些浏览器中导致弹出警告框,询问用户是否要下载文件。使用a标签通用性会更好。
此外,还可以使用 downloadjs 库来简化下载文件的过程,无需创建 URL 和 a 元素。downloadjs库更加强大,可以将文件直接下载到浏览器中,并且支持跨浏览器和跨平台。
const download = require('downloadjs');
const axios = require('axios');
axios({
url: 'http://example.com/file.pdf',
method: 'GET',
responseType: 'blob',
}).then((response) => {
download(response.data, 'file.pdf');
});