前端实现文件下载

前言

前端开发过程中,总会遇到点击链接下载。这个时候可以借助 2 种方法解决。一种是用 a 标签的 download,第二种是按钮点击之后调用接口来下载。2 种方法最好确定文件没有跨域现象。

a 标签 download

1
2
3
4
5
6
7
8
9
//点击按钮或者什么,生成a链接,然后将文件地址放在上面
downloadFile(url, fileName) {
let aLink = document.createElement("a");
document.body.appendChild(aLink);
aLink.setAttribute("href", url);
aLink.setAttribute("download", fileName);
aLink.click();
document.body.removeChild(aLink);
},

ajax 或者 fetch 访问下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* @description:
* @param {*} url 目标文件地址
* @param {*} filename 目标文件名
* @return {*}
* @Date: 2021-02-26 10:05:51
* @Author: David
*/
downloadFile(url, filename) {
this.getBlob(url, function(blob) {
this.saveAs(blob, filename);
});
},
getBlob(url, cb) {
let xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (xhr.status === 200) {
cb(xhr.response);
}
};
xhr.send();
}

/**
* @description: 保存
* @param {*} blob
* @param {*} filename 想要保存的文件名称
* @return {*}
* @Date: 2021-02-26 10:05:32
* @Author: David
*/
saveAs(blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
var body = document.querySelector("body");
link.href = window.URL.createObjectURL(blob);
link.download = filename;
// fix Firefox
link.style.display = "none";
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
}