在前端Web开发中,下载文件是一个很常见的需求,也有一些比较特殊的Case,比如下载文件请求是一个POST、url不是同源的、批量下载文件等。本文就介绍下几种download解决方案,以及特殊Case的最佳方案选择。
1 |
<a href={url} target="_blank">download</a> |
1 2 |
window.location.href = url; // 当前tab window.open(url); // 新tab |
缺点:
1.只支持get请求,不支持post请求。
2.浏览器会根据header的content-type来判断是下载文件还是预览文件。
比如 txt png 等格式文件,会在当前tab或新tab中预览,而不是下载下来。
3.由于只支持get,会有url参数过长问题。
4.不能加request header,无法做权限验证等逻辑。
5.不支持自定义file name。
通过HTML a标签的原生属性,使用浏览器下载。
https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/a#attr-download
1 |
<a href={url} download={fileName}>download</a> |
1 2 3 4 5 6 7 8 9 |
function downloadFile(url, fileName) { const a = document.createElement('a'); a.style.display = 'none'; a.href = url; a.download = fileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); } |
优点:
缺点:
API发送请求的方式,获取文件blog对象,然后通过URL.createObjectURL方法获取download url,然后用方案二的<a download />方式下载。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// 封装一个fetch download方法 async function fetchDownload(fetchUrl, method = "POST", body = null) { const response = await window.fetch(fetchUrl, { method, body: body ? JSON.stringify(body) : null, headers: { "Accept": "application/json", "Content-Type": "application/json", "X-Requested-With": "XMLHttpRequest", }, }); const fileName = getFileName(response); const blob = await response.blob(); const url = URL.createObjectURL(blob); return { blob, url, fileName }; // 返回blob、download url、fileName } // 根据response header获取文件名 function getFileName(response) { const disposition = response.headers.get('Content-Disposition');
// 本例格式是:"attachment; filename="img.jpg"" let fileName = disposition.split('filename=')[1].replaceAll('"', '');
// 可以根据自己的格式来截取文件名 // 参考https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Disposition // let fileName = ''; // if (disposition && disposition.indexOf('attachment') !== -1) { // const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(disposition); // fileName = matches?.[1]?.replace(/['"]/g, ''); // } fileName = decodeURIComponent(fileName); return fileName; } |
1 2 3 4 5 6 7 8 9 |
// 页面里调用 // get fetchDownload('/api/get/file?name=img.jpg', 'GET').then(({ blob, url, fileName }) => { downloadFile(url, fileName); // 调用方案二的download方法 }); // post fetchDownload('/api/post/file', 'POST', { name: 'img.jpg' }).then(({ blob, url, fileName }) => { downloadFile(url, fileName); }); |
URL.createObjectURL 生成的url如果过多会有效率问题,可以在合适的时机(download后)释放掉。参考:developer.mozilla.org/zh-CN/docs/…
1 2 3 4 5 |
if (window.URL) { window.URL.revokeObjectURL(url); } else { window.webkitURL.revokeObjectURL(url); } |
优点:
缺点:
有些需求是,点一个按钮需要把多个文件同时download下来,有以下几个方案可以实现。
1 2 3 |
downloadFile("/files/file1.txt", "file1.txt"); downloadFile("/files/word1.docx", "word1.docx"); downloadFile("/files/img1.jpg", "img1.jpg"); |
利用上面的方案二的<a download />方式下载,会触发浏览器是Download multiple files提示,如果选了Allow则会正常下载。
尝试每个download之间加延迟,依然会弹提示。这个应该是浏览器机制问题了,没办法避免了。
前端可以通过一个第三方库 jszip,可以把多个文件以blob、base64或纯文本等形式,按自定义的文件结构,压缩成一个zip文件,然后通过浏览器download下来。
官网:stuk.github.io/jszip/ 用法不难,直接看code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// 先封装一个方法,请求返回文件blob async function fetchBlob(fetchUrl, method = "POST", body = null) { const response = await window.fetch(fetchUrl, { method, body: body ? JSON.stringify(body) : null, headers: { "Accept": "application/json", "Content-Type": "application/json", "X-Requested-With": "XMLHttpRequest", }, }); const blob = await response.blob(); return blob; }
const zip = new JSZip(); zip.file("Hello.txt", "Hello World\n"); // 支持纯文本等
zip.file("img1.jpg", fetchBlob('/api/get/file?name=img.jpg', 'GET')); // 支持Promise类型,需要返回数据类型是 String, Blob, ArrayBuffer, etc zip.file("img2.jpg", fetchBlob('/api/post/file', 'POST', { name: 'img.jpg' })); // 同样支持post请求,只要返回类型正确就行
const folder1 = zip.folder("folder01"); // 创建folder folder1.file("img3.jpg", fetchBlob('/api/get/file?name=img.jpg', 'GET')); // folder里创建文件
zip.generateAsync({ type: "blob" }).then(blob => { const url = window.URL.createObjectURL(blob); downloadFile(url, "test.zip"); }); |
jszip还支持一些别的类型文件压缩,比如纯文本、base64、binary等等,详见:https://stuk.github.io/jszip/documentation/api_jszip/file_data.html
由于走的是纯前端压缩,所以会有延迟问题,走到最后download时才会调起浏览器下载,所以页面可能需要一个效果来更新压缩进度。zip.generateAsync方法就支持第二个参数,支持进度更新:
1 2 3 4 |
zip.generateAsync({ type: "blob" }, metadata => { const progress = metadata.percent.toFixed(2); // 保留2位小数 console.log(metadata.currentFile, "progress: " + progress + " %"); }).then(blob => ... ); |
后台加个api,然后把需要download的文件在后台压缩成zip,然后把文件流输出出来。然后就和单个文件download一样了。
因为后台会先压缩,会有延迟才会把blob返回前台,而且需要传多个文件信息,一般是post请求,所以建议使用单个文件下载的方案三通过API请求实现,在请求前后加上提示语或loading效果。
本文介绍了前端单个文件的下载方案,以及批量多个文件下载的解决方案。最后整理下方案建议:
单个文件下载:
批量文件下载: