这篇文章主要介绍了JS如何实现单个或多个文件批量下载的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇JS如何实现单个或多个文件批量下载文章都会有所收获,下面我们一起来看看吧。
单个文件Download
方案一:location.href or window.open
<a href="https://www.maopiaopiao.com">
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。
方案二:通过a标签的download属性
通过HTML a标签的原生属性,使用浏览器下载。
https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/a#attr-download
<a href="https://www.maopiaopiao.com">
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);
}优点:
都是走的浏览器下载文件逻辑,不会预览文件。
当前tab打开方式下载。
支持设置file name。
缺点:
只支持get请求,不支持post请求。
不能加
request header,无法做权限验证等逻辑。
不支持跨域地址。
方案三:API请求
API发送请求的方式,获取文件
blog对象,然后通过
URL.createObjectURL方法获取download url,然后用方案二的
<a download />方式下载。
// 封装一个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[^;=
]*=((['"]).*?2|[^;
]*)/.exec(disposition);
    //     fileName = matches?.[1]?.replace(/['"]/g, '');
    // }
    fileName = decodeURIComponent(fileName);
    return fileName;
}// 页面里调用
// 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后)释放掉。
if (window.URL) {
    window.URL.revokeObjectURL(url);
} else {
    window.webkitURL.revokeObjectURL(url);
}优点:
因为最后用的是方案二,所以满足方案二的优点。
支持post请求、支持跨域(fetch本身支持)。
可以加
request header。
缺点:
低版本浏览器不支持,可以通过
'download' in document.createElement('a')判断是否支持。浏览器兼容可能有问题,比如Safari、IOS Safari。
多个文件批量Download
有些需求是,点一个按钮需要把多个文件同时download下来,有以下几个方案可以实现。
方案一:按单个文件download方式,循环依次下载
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之间加延迟,依然会弹提示。这个应该是浏览器机制问题了,没办法避免了。
方案二:前端打包成zip download
前端可以通过一个第三方库
jszip,可以把多个文件以blob、base64或纯文本等形式,按自定义的文件结构,压缩成一个zip文件,然后通过浏览器download下来。
官网:stuk.github.io/jszip/ 用法不难,直接看code:
// 先封装一个方法,请求返回文件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
"); // 支持纯文本等
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等等。
由于走的是纯前端压缩,所以会有延迟问题,走到最后download时才会调起浏览器下载,所以页面可能需要一个效果来更新压缩进度。
zip.generateAsync方法就支持第二个参数,支持进度更新:
zip.generateAsync({ type: "blob" }, metadata => {
    const progress = metadata.percent.toFixed(2); // 保留2位小数
    console.log(metadata.currentFile, "progress: " + progress + " %");
}).then(blob => ... );方案三:后端压缩成zip,然后以文件流url形式,前端调用download
后台加个api,然后把需要download的文件在后台压缩成zip,然后把文件流输出出来。然后就和单个文件download一样了。
因为后台会先压缩,会有延迟才会把blob返回前台,而且需要传多个文件信息,一般是post请求,所以建议使用单个文件下载的方案三通过API请求实现,在请求前后加上提示语或loading效果。