<button onclick="handleClick()">立即下载</button>
<iframe name="myIframe" style="display:none"></iframe>
<script>
const handleClick = () => {
window.open('/download/1.png', 'myIframe');
}
</script>
批量下载
批量下载和单个下载也没什么区别嘛,就多执行几次下载而已嘛。这样也确实没什么问题。如果把这么多个文件打包成一个压缩包,再只下载这个压缩包,是不是体验起来就好一点了呢。
文件打包
archiver 是一个在 Node.js 中能跨平台实现打包功能的模块,支持 zip 和 tar 格式。
const router = require('koa-router')();
const send = require('koa-send');
const archiver = require('archiver');router.post('/downloadAll', async (ctx){
// 将要打包的文件列表
const list = [{name: '1.txt'},{name: '2.txt'}];
const zipName = '1.zip';
const zipStream = fs.createWriteStream(zipName);
const zip = archiver('zip');
zip.pipe(zipStream);
for (let i = 0; i < list.length; i++) {
// 添加单个文件到压缩包
zip.append(fs.createReadStream(list[i].name), { name: list[i].name })
}
await zip.finalize();
ctx.attachment(zipName);
await send(ctx, zipName);
})
如果直接打包整个文件夹,则不需要去遍历每个文件 append 到压缩包里
const zipStream = fs.createWriteStream('1.zip');
const zip = archiver('zip');
zip.pipe(zipStream);
// 添加整个文件夹到压缩包
zip.directory('upload/');
zip.finalize();
注意:打包整个文件夹,生成的压缩包文件不可存放到该文件夹下,否则会不断的打包。
中文编码问题
当文件名含有中文的时候,可能会出现一些预想不到的情况。所以上传时,含有中文的话我会对文件名进行 encodeURI() 编码进行保存,下载的时候再进行 decodeURI() 解密。
ctx.attachment(decodeURI(path));
await send(ctx, path);ctx.attachment 将 Content-Disposition 设置为 “附件” 以指示客户端提示下载。通过解码后的文件名作为下载文件的名字进行下载,这样下载到本地,显示的还是中文名。
然鹅, koa-send 的源码中,会对文件路径进行 decodeURIComponent() 解码:
// koa-send
path = decode(path)function decode (path) {
try {
return decodeURIComponent(path)
} catch (err) {
return -1
}
}
这时解码后去下载含中文的路径,而我们服务器中存放的是编码后的路径,自然就找不到对应的文件了。









