原理
使用window.URL.createObjectURL和window.URL.revokeObjectURL method和blob对象实现文件下载
精简版封装
1 | /** |
更好的封装
1 | var URL = window.URL || window.webkitURL; |
最佳方案
直接使用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
20var 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();