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

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

问题描述

我正在使用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有一个附加方法,可以将文本保存为文件。要将数据流到用户,您可以简单地将其传送到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.

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

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