首页 > 解决方案 > 使用 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');

标签: node.jsexpressarchivenode-archiver

解决方案


我认为您也需要关闭响应流:

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();
});

推荐阅读