Skip to content

如何使用JavaScript下载pdf等文件 #17

Open
@gnipbao

Description

@gnipbao

articleocw-59983b4f358aa

原理

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

精简版封装

/**
 * 创建并下载文件
 * @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);
}

在线实例

更好的封装

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以下不支持注意兼容性)

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();

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions