js实现点击浏览器自动下载

记录一下用纯js实现各种浏览器自动下载的功能。
兼容IE。

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
downloadDocument("YOUR DOCUMENT");

function downloadDocument(pdfType) {
// your defination of file url and file name
let fileUrl = documentInfo[pdfType]["url"];
let fileName = `${documentInfo[pdfType]["name"]}.pdf`;

const oReq = new XMLHttpRequest();
oReq.open("GET", fileUrl, true);
oReq.responseType = "blob";
oReq.onload = function () {
const fileBlob = new Blob([oReq.response], {
// or other type
type: "application/pdf",
});
saveAs(fileBlob, fileName);
};
oReq.send();
}

function saveAs(blob, filename) {
const URL = window.URL || window.webkitURL
const type = blob.type
const force_saveable_type = 'application/octet-stream'
const slice = blob.slice || blob.webkitSlice || blob.mozSlice
blob = slice.call(blob, 0, blob.size, force_saveable_type)
const url = URL.createObjectURL(blob)
const save_link = document.createElementNS(
"http://www.w3.org/1999/xhtml",
"a"
);
save_link.href = url;
save_link.download = filename;

const event = new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window,
});
save_link.dispatchEvent(event);
URL.revokeObjectURL(url);
}