前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Nodejs和Express构建http响应流实现下载功能

使用Nodejs和Express构建http响应流实现下载功能

作者头像
kongxx
发布2023-11-22 10:22:22
2910
发布2023-11-22 10:22:22
举报

首先创建一个文件流来读取要下载的文件,当然可以是动态产生的输入流

代码语言:javascript
复制
const fileStream = fs.createReadStream('test.zip');

然后创建响应头,指定响应的类型,同时也可以使用Content-Disposition设置浏览器下载时需要保存的文件名

代码语言:javascript
复制
const head = {
    'Content-Type': 'application/zip, application/octet-stream; charset=ISO-8859-1',
    'Content-Disposition': 'attachment;filename=\"resources123.zip\"'
  };
res.writeHead(200, head);

最后通过文件流的pipe()方法输出到响应里

代码语言:javascript
复制
fileStream.pipe(res);

完整router代码如下

代码语言:javascript
复制
router.get('/download', function(req, res, next) {
    const fileStream = fs.createReadStream('test.zip');
    const head = {
        'Content-Type': 'application/zip, application/octet-stream; charset=ISO-8859-1',
        'Content-Disposition': 'attachment;filename=\"test123.zip\"'
      };
    res.writeHead(200, head);
    fileStream.pipe(res);
});

最后说一下,express里的response也提供了一个attachment()方法,这个方法会设置Content-Disposition头,并且会通过res.type()来设置Content-Type头,代码如下

代码语言:javascript
复制
router.get('/download', function(req, res, next) {
    const fileStream = fs.createReadStream('test.zip');
    res.attachment('test123.zip');
    fileStream.pipe(res);
});

最后的最后,看一下如果出错了应该怎么处理

代码语言:javascript
复制
router.get('/download', function(req, res, next) {
    const fileStream = fs.createReadStream('test.zip');
    fileStream.on('open', () => {
        res.attachment('test123.csv');
        fileStream.pipe(res);
    });
    fileStream.on('error', err => {
        next(err);
    });
});
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-11-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档