创建并发送 Zip 文件 -NODE JS [英] Create and Send Zip file -NODE JS

查看:59
本文介绍了创建并发送 Zip 文件 -NODE JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建 zip 文件,然后将其发送给客户端.我知道如何创建它,但我在将它发送给客户时遇到了问题.我尝试了很多方法.我正在从客户端发送 POST 请求,作为响应,我想发送一个文件.这是我的服务器站点示例代码

I'm trying to create and then send zip file to client. I know how to create it but I've got a problem with send it to client. I tried many ways. I'm sending POST request from Client and as response I want to send a file. This is my server-site example code

var Zip = require('node-zip');
router.post('/generator', function(req, res, next) {
    var zip = new Zip;

    zip.file('hello.txt', 'Hello, World!');
    var options = {base64: false, compression:'DEFLATE'};
    fs.writeFile('test1.zip', zip.generate(options), 'binary', function (error) {
        console.log('wrote test1.zip', error);
    });
    res.setHeader('Content-disposition', 'attachment; filename=test1.zip');
    res.download('test1.zip');

}

});我也尝试过这样的事情:

}); I also tried something like this:

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);
  filestream.pipe(res);

我尝试使用以下库:

  1. 节点压缩

  1. node-zip

存档器

谁能告诉我怎么做?

推荐答案

我之前没有使用过 node-zip 或存档器(我通常只使用内置的 zlib 模块),但我马上注意到的一件事是您应该将 res.download 放在 writeFile 的回调中.这样它只会在文件完全写入磁盘后发送.

I haven't worked with node-zip or archiver before (I usually just use the built-in zlib module), but one thing I noticed right away is that you should place res.download inside the callback of writeFile. That way it will only send the file once it has been fully written to disk.

fs.writeFile('test1.zip', zip.generate(options), 'binary', function (error) {
    res.download('test1.zip');
});

我希望这个解决方案对你有用,如果它不方便发表评论.

I hope this solution works for you, if it doesn't feel free to comment.

另外,我认为 res.download 为您设置了 Content-disposition 标头,您不需要手动设置它.虽然不是 100% 确定那个.

Also, I think res.download sets the Content-disposition header for you, you don't need to set it manually. Not 100% sure on that one though.

这篇关于创建并发送 Zip 文件 -NODE JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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