需求说明
我们开发普通的下载链接,只主要写一个<a href="path/to/file.pdf"></a>标签,不过有一些需求是要针对这个下载链接做权限校验,而权限校验需要在请求这个链接的时候,在Header里加上token之类的。
代码实现
使用axios来调用get请求,并发送自定义的Header,然后把请求到的数据组成下载内容,示例代码如下:
download() {
axios.get('http://192.168.1.1:8081/api/export_pdf', {
headers: {
'Content-Disposition': "attachment; filename=download.pdf",
'Content-Type': 'application/octet-stream',
'X-Token': 'xxyyzz123' // 自定义token
},
responseType: 'arraybuffer',//or responseType: 'blob', //important
}
).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', "download.pdf");
document.body.appendChild(link);
link.click();
link.remove();
}).catch((error) => console.log(error));
}
如果是POST请求,详见这篇:https://blog.terrynow.com/2021/08/09/axios-post-export-download-file/
文章评论