动态创建 zip 并将其流式传输到客户端 [英] Dynamically create and stream zip to client

查看:37
本文介绍了动态创建 zip 并将其流式传输到客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 NodeJs (w/express) 并且我正在尝试将一个 zip 文件流回客户端.zip 中包含的文件不在文件系统中,而是动态创建的.我想将文件内容流式传输到 zip 并将 zip 流式传输回客户端.

I am using NodeJs (w/express) and I am trying to stream a zip file back to the client. The files contained in the zip do not live on the file system, rather they are created dynamically. I would like to stream the file(s) content to the zip and stream the zip back to the client.

I.E.我希望客户收到:

I.E. I want the client to receive:

tmp.zip
 --> 1.txt
 --> 2.txt
 --> 3.txt

动态创建 1,2,3.txt 并流式传输到 zip 文件.这可能吗?

Where 1,2,3.txt are created on the fly and streamed to the zip file. Is this possible?

推荐答案

Archiver has an append使您可以将文本另存为文件的方法.要将数据流式传输"给用户,您可以简单地通过管道传输到 HTTP 响应对象.

Archiver has an append method that lets you save text as a file. To "stream" that data to the user you can simply pipe to the HTTP response object.

var Http = require('http');
var Archiver = require('archiver');

Http.createServer(function (request, response) {
    // Tell the browser that this is a zip file.
    response.writeHead(200, {
        'Content-Type': 'application/zip',
        'Content-disposition': 'attachment; filename=myFile.zip'
    });

    var zip = Archiver('zip');

    // Send the file to the page output.
    zip.pipe(response);

    // Create zip with some files. Two dynamic, one static. Put #2 in a sub folder.
    zip.append('Some text to go in file 1.', { name: '1.txt' })
        .append('Some text to go in file 2. I go in a folder!', { name: 'somefolder/2.txt' })
        .file('staticFiles/3.txt', { name: '3.txt' })
        .finalize();

}).listen(process.env.PORT);

这将创建一个包含两个文本文件的 zip 文件.访问此页面的用户将看到文件下载提示.

This will create a zip file with the two text files. The user visiting this page will be presented with a file download prompt.

这篇关于动态创建 zip 并将其流式传输到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆