[英]How to pipe a WriteStream concatenating an extension?
I am new in NodeJS. 我是NodeJS的新手。 I know we can stream data to the client by using pipe() method.
我知道我们可以使用pipe()方法将数据流式传输到客户端。
Here is the snippet of the code 这是代码片段
router.get('/archive/*', function (req, res) {
var decodedURI = decodeURI(req.url);
var dirarr = decodedURI.split('/');
var dirpath = path.join(dir, dirarr.slice(2).join("/"));
console.log("dirpath: " + dirpath);
var archive = archiver('zip', {
zlib: {level: 9} // Sets the compression level.
});
archive.directory(dirpath, 'new-subdir');
archive.on('error', function (err) {
throw err;
});
archive.pipe(res)
archive.on('finish', function () {
console.log("finished zipping");
});
archive.finalize();
});
when I use a get request the zipped file downloaded but without any extension . 当我使用get请求时,下载的压缩文件没有任何扩展名 。 I know its because I am piping a writestream into the response.
我知道它是因为我正在将写入流传送到响应中。 Is there anyway pipe it with a .zip extension ?
反正有.zip扩展名吗? Or How can I send the zip file without building the zip file in HDD ?
或者,如何在没有在HDD中构建zip文件的情况下发送zip文件?
You can use res.attachment()
to both set the filename of the download, and also its mime-type: 您可以使用
res.attachment()
来设置下载的文件名,以及它的mime类型:
router.get('/archive/*', function (req, res) {
res.attachment('archive.zip');
...
});
One of the ways is to change Headers before piping, 一种方法是在管道之前更改标题,
res.setHeader("Content-Type", "application/zip");
res.setHeader('Content-disposition' ,'attachment; filename=downlaod.zip');
For the Given Code, 对于给定的代码,
router.get('/archive/*', function (req, res) {
var decodedURI = decodeURI(req.url);
var dirarr = decodedURI.split('/');
var dirpath = path.join(dir, dirarr.slice(2).join("/"));
var output = fs.createWriteStream(__dirname + '/7.zip');
var archive = archiver('zip', {
zlib: {level: 9} // Sets the compression level.
});
archive.directory(dirpath, 'new-subdir');
archive.on('error', function (err) {
throw err;
});
res.setHeader("Content-Type", "application/zip");
res.setHeader('Content-disposition' ,'attachment; filename=downlaod.zip');
archive.pipe(res);
archive.finalize();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.