You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS后端如何将字符串内容打包为Zip文件并发送给前端

在NestJS中直接将字符串打包为Zip并返回Buffer给前端

完全可以不用生成真实文件,直接在内存中将字符串打包成Zip并转为Buffer返回给前端,用archiver库就能轻松实现,下面是具体的实现步骤和代码:

1. 安装依赖

先安装archiver库:

npm install archiver
# 或者用yarn
yarn add archiver

2. 实现打包并返回的Controller方法

在你的NestJS控制器中添加如下方法:

import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';
import * as archiver from 'archiver';

@Controller('download')
export class DownloadController {
  @Get('zip')
  async downloadZip(@Res() res: Response) {
    // 你的四个文本内容
    const textFileContentOne = 'This should be the content of the first .txt file';
    const textFileContentTwo = 'This should be the content of the second .txt file';
    const textFileContentThree = 'This should be the content of the third .txt file';
    const textFileContentFour = 'This should be the content of the fourth .txt file';

    // 设置响应头,告诉浏览器这是一个Zip文件
    res.setHeader('Content-Type', 'application/zip');
    res.setHeader('Content-Disposition', 'attachment; filename="text-files.zip"');

    // 创建archiver实例,指定压缩格式为zip
    const archive = archiver('zip', {
      zlib: { level: 9 } // 设置压缩级别,9为最高
    });

    // 监听错误事件
    archive.on('error', (err) => {
      throw err;
    });

    // 将archiver的输出流pipe到响应对象
    archive.pipe(res);

    // 逐个添加文本内容到Zip中,每个对应一个txt文件
    archive.append(textFileContentOne, { name: 'file1.txt' });
    archive.append(textFileContentTwo, { name: 'file2.txt' });
    archive.append(textFileContentThree, { name: 'file3.txt' });
    archive.append(textFileContentFour, { name: 'file4.txt' });

    // 完成打包
    await archive.finalize();
  }
}

代码说明

  • archiver.append()方法可以直接接收字符串内容,第二个参数指定Zip中的文件名,完全不需要生成本地文件
  • 通过archive.pipe(res)直接将压缩后的内容流式返回给前端,也可以先收集成Buffer再返回(如果需要的话)
  • 设置正确的Content-Type和Content-Disposition响应头,前端会自动触发“另存为”窗口

如果你确实需要先得到Zip的Buffer再处理(比如存储或者其他逻辑),可以用内存流来收集:

import { PassThrough } from 'stream';
import * as archiver from 'archiver';

async function createZipBuffer() {
  const archive = archiver('zip', { zlib: { level: 9 } });
  const stream = new PassThrough();
  const chunks: Buffer[] = [];

  stream.on('data', (chunk) => chunks.push(chunk));

  archive.pipe(stream);
  archive.append(textFileContentOne, { name: 'file1.txt' });
  archive.append(textFileContentTwo, { name: 'file2.txt' });
  archive.append(textFileContentThree, { name: 'file3.txt' });
  archive.append(textFileContentFour, { name: 'file4.txt' });
  await archive.finalize();

  return new Promise<Buffer>((resolve) => {
    stream.on('finish', () => {
      resolve(Buffer.concat(chunks));
    });
  });
}

// 调用方法得到Buffer
const zipBuffer = await createZipBuffer();
// 然后可以自己处理这个buffer,比如发送给前端
sendBufferToFrontend(zipBuffer);

内容的提问来源于stack exchange,提问作者sirzento

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:36:08