如何使用JavaScript下载文件

articleocw-59983b4f358aa

原理

使用window.URL.createObjectURLwindow.URL.revokeObjectURL method和blob对象实现文件下载

精简版封装

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 创建并下载文件
* @param {String} fileName 文件名
* @param {String} content 文件内容
*/
function saveAs(content, filename) {
var link = document.createElement('a');
var blob = new Blob([content]);
link.download = filename;
link.href = URL.createObjectURL(blob);
link.click();
URL.revokeObjectURL(blob);
}

在线实例

更好的封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var URL = window.URL || window.webkitURL;
function saveAs(blob, filename) {
var type = blob.type;
var force_saveable_type = 'application/octet-stream';
if (type && type != force_saveable_type) { // 强制下载,而非在浏览器中打开
var slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
}
var url = URL.createObjectURL(blob);
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = url;
save_link.download = filename;

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

在线实例

最佳方案

直接使用FileSaver库。也许在某些浏览器需要实现Blob对象可以使用Blob.js。(ps:IE10以下不支持注意兼容性)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var oReq = new XMLHttpRequest();
// The Endpoint of your server
var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
// Configure XMLHttpRequest
oReq.open("GET", URLToPDF, true);
// Important to use the blob response type
oReq.responseType = "blob";
// When the file request finishes
// Is up to you, the configuration for error events etc.
oReq.onload = function() {
// Once the file is downloaded, open a new window with the PDF
// Remember to allow the POP-UPS in your browser
var file = new Blob([oReq.response], {
type: 'application/pdf'
});

// Generate file download directly in the browser !
saveAs(file, "mypdffilename.pdf");
};
oReq.send();