文件下载

业务中常遇到前端下载文件的需求,简单汇总。

返回Blob下载表格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
this.$http.get('***', {
responseType: 'blob'
}).then(data){
let blob = new Blob([data], {
type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob)
} else {
let elink = document.createElement('a')
elink.download = `${fileName}.xls`
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
document.body.removeChild(elink)
}
}

返回Blob下载pdf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
...
let blob = new Blob([data], {
type: 'application/pdf;charset=UTF-8'
});
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob);
} else {
let elink = document.createElement('a');
elink.download = `${fileName}.pdf`;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
}
})

返回url下载

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
..._URL...

// location.href
location.href = _URL;

// window.open
window.open(_URL);

// iframe
let iframe = document.createElement('iframe');
iframe.style.display = 'none'; // 防止影响页面
iframe.style.height = 0; // 防止影响页面
iframe.src = _URL;
document.body.appendChild(iframe);
setTimeout(() => {
iframe.remove();
}, 60 * 1000);

// blob
let Req = new XMLHttpRequest();
Req.open('GET', _URL, true);
Req.responseType = 'blob';
Req.onload = () => {
var blob = new Blob([Req.response], {
type: 'application/pdf'
});
let type = blob.type;
let forceSaveableType = 'application/octet-stream';
if (type && type !== forceSaveableType) {
// 强制下载,而非在浏览器中打开
let slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call(blob, 0, blob.size, forceSaveableType);
}
let url = URL.createObjectURL(blob);
let saveLink = document.createElementNS(
'http://www.w3.org/1999/xhtml',
'a'
);
saveLink.href = url;
saveLink.download = '文件.pdf';
let event = new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
});
saveLink.dispatchEvent(event);
URL.revokeObjectURL(url);
};
Req.send();

第三方

具体见文档https://github.com/rndme/download

1
download('文件.pdf')
------本文结束 感谢阅读------