【问题标题】:Creating zip using express and archiver使用 express 和 archiver 创建 zip
【发布时间】:2019-03-04 23:56:29
【问题描述】:

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

为什么 zip 文件在通过 express res 对象发送时会损坏?解决办法是什么?

编辑: 如果我使用输出格式为tar 而不是 zip,它可以正常工作。

const arch = archiver('tar');

【问题讨论】:

    标签: node.js express archive node-archiver


    【解决方案1】:

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

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

    【讨论】:

    • 刚试过。它没有用。如果归档器格式为 tar,则无需使用 res.end() 关闭流即可
    猜你喜欢
    • 1970-01-01
    • 2016-08-06
    • 2021-06-24
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2019-04-02
    相关资源
    最近更新 更多