0

我是 NodeJS 的新手。我知道我们可以使用 pipe() 方法将数据流式传输到客户端。

这是代码片段

 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();

    });

当我使用获取请求时,下载的压缩文件但 没有任何扩展名。我知道它是因为我正在将写入流传输到响应中。反正有没有.zip扩展名的管道?或者如何在不在 HDD 中构建 zip 文件的情况下发送 zip 文件?

4

2 回答 2

1

一种方法是在管道之前更改标题,

res.setHeader("Content-Type", "application/zip");
res.setHeader('Content-disposition' ,'attachment; filename=downlaod.zip');

对于给定的代码,

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();

    });
于 2017-07-02T14:09:18.670 回答
1

您可以使用res.attachment()来设置下载的文件名,以及它的 mime 类型:

router.get('/archive/*', function (req, res) {
  res.attachment('archive.zip');
  ...
});
于 2017-07-02T13:33:40.933 回答