【问题标题】:Zip image stream using archiver and send as express response使用归档器压缩图像流并作为快速响应发送
【发布时间】:2022-01-09 00:19:39
【问题描述】:

这是在 Node/Express/Typescript 上。我正在尝试在我的文件系统上获取图像,将其流式传输到 zip 文件,然后将此 zip 文件流式传输到客户端。我必须确保每一步都是流式传输的,因为这将扩展为压缩多个文件,这些文件需要作为 zip 流式传输到客户端。

我有以下代码:

import express, { Application, Request, Response } from "express";
import fs from "fs";
import stream from "stream";
import archiver from "archiver";

app.get("/images", async (req: Request, res: Response) => {
    const r = fs.createReadStream("appicon.png");
    const ps = new stream.PassThrough();

    // stream the image
    stream.pipeline(
        r,
        ps,
        (err) => {
            if (err) {
                console.log(err);
                return res.sendStatus(400);
            }
        }
    );


    // zip the image and send it
    let archive = archiver("zip");

    archive.on("end", () => {
        console.log(archive.pointer() + " total bytes");
        console.log("archiver finalized");
    })

    archive.on('error', (err) => {
        return res.status(500).send({
            message: err
        });
    })

    res.attachment('output.zip');
    ps.pipe(archive); 
    archive.pipe(res);



    archive.finalize();

});

但是,当我访问我的 /images 路由时,我得到了一个空的 output.zip 文件。

我觉得我以某种方式弄乱了管道的顺序。

我错过了什么?

【问题讨论】:

  • 输出结束事件是否曾经触发?我没有看到你在哪里定义了输出
  • 那是 appicon.png 的正确路径吗?也许试试“./appicon.png”。
  • 是的,如果我删除所有存档代码并执行 ps.pipe(res); 我可以在浏览器上看到图像加载。
  • 我的日志中实际上没有收到“归档完成”消息

标签: javascript node.js typescript express


【解决方案1】:

我发现了这个问题。这是有效的代码:

app.get("/images", async (req: Request, res: Response) => {
    const r = fs.createReadStream("appicon.png");
    const ps = new stream.PassThrough();

    stream.pipeline(
        r,
        ps,
        (err) => {
            if (err) {
                console.log(err);
                return res.sendStatus(400);
            }
        }
    );

    //r.pipe(ps); // alternative way to do it without pipeline


    // zip the image and send it
    let archive = archiver("zip");

    archive.on("end", () => {
        console.log(archive.pointer() + " total bytes");
        console.log("archiver finalized");
    })

    archive.on('error', (err) => {
        return res.status(500).send({
            message: err
        });
    })

    // name the output file
    res.attachment("output.zip");

    // pipe the zip to response
    archive.pipe(res);

    // add the image from stream to archive
    archive.append(ps, {name: "image.png"});

    archive.finalize();

});

我必须使用 archive.append(ps, {name: "image.png"}); 将我的图像流添加到 zip 存档中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 2013-12-02
    相关资源
    最近更新 更多