0%

JS 携带参数下载文件

Axios

1
2
3
4
5
6
7
8
9
10
11
12
axios({
url: 'http://api.dev/file-download', //your url
method: 'GET',
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', 'file.pdf'); //or any other extension
document.body.appendChild(link);
link.click();
});

Fetch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let anchor = document.createElement('a');
document.body.appendChild(anchor);
let file = 'https://www.example.com/some-file.pdf';

let headers = new Headers();
headers.append('Authorization', 'Bearer MY-TOKEN');

fetch(file, { headers })
.then((response) => response.blob())
.then((blobby) => {
let objectUrl = window.URL.createObjectURL(blobby);

anchor.href = objectUrl;
anchor.download = 'some-file.pdf';
anchor.click();

window.URL.revokeObjectURL(objectUrl);
});

参考文章