JS生成下载文件
常用方式:
/** * 生成下载文件 * @param {Object} filename * @param {Object} text */ function download(filename, text) { var pom = document.createElement('a'); pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); pom.setAttribute('download', filename); if (document.createEvent) { var event = document.createEvent('MouseEvents'); event.initEvent('click', true, true); pom.dispatchEvent(event); } else { pom.click(); } }
常用方式改进版(推荐):
转成文件再下载,字符串/文件 特别大时(上百兆)此处理方式内存不会溢出
/** * 生成下载文件 * @param {Object} filename 文件名 * @param {Object} text 内容 */ function download(filename, text) { var urlObject = window.URL || window.webkitURL || window; var export_blob = new Blob([text]); var save_link = document.createElement("a") save_link.href = urlObject.createObjectURL(export_blob); save_link.download = filename; if (document.createEvent) { var event = document.createEvent('MouseEvents'); event.initEvent('click', true, true); save_link.dispatchEvent(event); } else { save_link.click(); } }
其它:
/** * 将url文件下载到本地 * @param fileUrl {String} 文件链接 * @param fileName {String} 文件名字 * @return void */ async function downloadFile(fileUrl,fileName) { let blob = await getBlob(fileUrl); saveFile(blob, fileName); }
function getBlob(fileUrl) { return new Promise(resolve => { const xhr = new XMLHttpRequest(); xhr.open('GET', fileUrl, true); //监听进度事件 xhr.addEventListener( 'progress', function (evt) { if (evt.lengthComputable) { let percentComplete = evt.loaded / evt.total; // percentage是当前下载进度,可根据自己的需求自行处理 let percentage = percentComplete * 100; } }, false ); xhr.responseType = 'blob'; xhr.onload = () => { if (xhr.status === 200) { resolve(xhr.response); } }; xhr.send(); }); }
function saveFile(blob, fileName) { // ie的下载 if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, filename); } else { // 非ie的下载 const link = document.createElement('a'); const body = document.querySelector('body'); link.href = window.URL.createObjectURL(blob); link.download = fileName; // fix Firefox link.style.display = 'none'; body.appendChild(link); link.click(); body.removeChild(link); window.URL.revokeObjectURL(link.href); } }