ajax下载小于500M大文件【原】
不推荐使用的FileReader
之前用FileReader读取下载文件,当文件超过1M浏览器就立即扑街了
// 文件下载 function download(blob, fileName) { var reader = new FileReader(); reader.readAsDataURL(blob); reader.onload = function (e) { //创建a标签,构造下载弹窗 var a = document.createElement("a"); a.id = "downloadTag"; a.download = fileName; a.href = e.target.result; $("body").append(a); a.click(); $("#downloadTag").remove(); console.log("下载完成!"); } }
blob方式推荐
于是在网上找到另一种Blob读取方式
核心代码
var blob=new Blob([xhrRequest.response], {type: 'application/octet-binary'});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="myFileName.zip"; link.click();
完整代码
request.js
/** * 通用下載文件方法 * @param {url, data} config */ fileDownload: function (config) { tool.loading() var xhrRequest = xhr(config.url); xhrRequest.addEventListener("load", function (data) { config.complete && config.complete(data) }, false); xhrRequest.addEventListener("error", function (data) { tool.loading('close') }, false); xhrRequest.onload = function (data) { if (this.status === 200) { var blob = new Blob([xhrRequest.response], { type: 'application/octet-binary' }); var contentDisposition = this.getResponseHeader('Content-Disposition'); var fileName = contentDisposition.split('=')[1]; download(blob, fileName) tool.loading('close') } } // 发送请求 xhrRequest.send(JSON.stringify(config.data)); // 文件下载 function download(blob, fileName) { var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); link.remove(); // var reader = new FileReader(); // reader.readAsDataURL(blob); // reader.onload = function (e) { // //创建a标签,构造下载弹窗 // var a = document.createElement("a"); // a.id = "downloadTag"; // a.download = fileName; // a.href = e.target.result; // $("body").append(a); // a.click(); // $("#downloadTag").remove(); // console.log("下载完成!"); // } } // request function xhr(url) { var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.responseType = "blob"; xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8"); xhr.setRequestHeader('token', storage.get('token')) return xhr } }
感觉空虚寂寞,只是因为你无所关注,无处付出。