我正在使用 NodeJs (w/express),并且尝试将 zip 文件流式传输回客户端。 zip 中包含的文件并不存在于文件系统中,而是动态创建的。我想将文件内容流式传输到 zip 并将 zip 流式传输回客户端。
IE。我希望客户收到:
tmp.zip
--> 1.txt
--> 2.txt
--> 3.txt
其中 1,2,3.txt 是动态创建的并流式传输到 zip 文件。这可能吗?
Archiver https://github.com/ctalkington/node-archiver有一个追加方法,可让您将文本保存为文件。要将数据“流式传输”给用户,您只需通过管道传输到 HTTP 响应对象即可。
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 文件。访问此页面的用户将看到文件下载提示。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)