node.js - 使用 express 和 archiver 创建 zip
问题描述
我使用 node-archiver 来压缩文件,如下所示。但我得到损坏的 zip 文件。
app.get('/download', async (req, res) => {
const arch = archiver('zip');
arch.append('abc', { name: 'abc.txt'});
arch.append('cdf', { name: 'cdf.txt'});
res.attachment('test.zip').type('zip');
arch.pipe(res);
arch.finalize();
});
我修改了代码直接保存到文件系统。使用此代码,我得到了在文件系统上创建的工作 zip 文件。
app.get('/download', async (req, res) => {
const arch = archiver('zip');
arch.append('abc', { name: 'abc.txt'});
arch.append('cdf', { name: 'cdf.txt'});
const output = fs.createWriteStream('./test.zip');
arch.pipe(output);
arch.finalize();
});
为什么通过 expressres
对象发送 zip 文件时会损坏?解决办法是什么?
编辑:
如果我使用输出格式tar
而不是 zip 它可以正常工作。
const arch = archiver('tar');
解决方案
我认为您也需要关闭响应流:
app.get('/download', async (req, res) => {
const arch = archiver('zip');
arch.append('abc', { name: 'abc.txt'});
arch.append('cdf', { name: 'cdf.txt'});
res.attachment('test.zip').type('zip');
arch.on('end', () => res.end()); // end response when archive stream ends
arch.pipe(res);
arch.finalize();
});
推荐阅读
- javascript - Vue.js 将变量从一个组件传递到另一个组件(jQuery)
- javascript - 移动 WebView 中的 Javascript 控制台
- python - 字典勾选框的总和列表
- node.js - 如何使用 node 和 npm 为 Material.io 组件正确设置开发环境?
- opengl - 将纹理采样到大网格的小区域
- r - R:在 dateRangeInput 之间指定日期-“seq.int 中的错误:'to' 必须是有限数”
- pyramid - Pyramid WebTest 没有捕捉到 ContextualVersionConflict
- javascript - 我如何向具有 ID 的特定用户发送 DM?
- jsp - 如何使任何人都可以访问 JSP 上传的文件?
- kubernetes - 如何在 kubernetes 中以非 root 用户身份挂载路径