eggjs实现文件下载

参考文章

exceljs-demo
createReadStream用法
egg-download example
exceljs
eggjs怎么实现文件下载?-知乎

理解实现

// 简单的
const filePath = '/path/to/file'
this.ctx.attachment(filePath)
// 相当于设置响应头 'content-disposition': `attachment; filename="??.xlsx"; filename*=UTF-8''%E8%A1%A8%E5%8D%95.xlsx`
this.ctx.set('Content-Type', 'application/octet-stream')
this.ctx.body = fs.createReadStream(filePath)

//我们要下载excel文件,可以这样设置
this.ctx.attachment('表单.xlsx')
this.ctx.type = '.xlsx'
//设置响应 Content-Type 通过 mime 字符串或文件扩展名。如:ctx.type = 'text/plain; charset=utf-8'; 或者 ctx.type = '.png';
this.ctx.body = await wb.xlsx.writeBuffer() // 这个是exceljs的方法
// 此时响应头为
header: [Object: null prototype] {
  'accept-ranges': 'bytes',
  'content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'content-disposition': `attachment; filename="??.xlsx"; filename*=UTF-8''%E8%A1%A8%E5%8D%95.xlsx`
}
// 会覆盖ctx.set设置的Content-Type

Egg 官方案例

  async download() {
    const filePath = path.resolve(this.app.config.static.dir, 'hello.txt');
    this.ctx.attachment('hello.txt');
    this.ctx.set('Content-Type', 'application/octet-stream');
    this.ctx.body = fs.createReadStream(filePath);
  }

  async downloadImage() {
    const url = 'http://cdn2.ettoday.net/images/1200/1200526.jpg';
    const res = await this.ctx.curl(url, {
      streaming: true,
    });

    this.ctx.type = 'jpg';
    this.ctx.body = res.res;
  }
}

知乎回答-egg 实现文件下载

转载知乎用户 @Jasin Yip 的回答,侵权立删。

1.简单实现
在这里插入图片描述
2.支持进度条和剩余时间(Content-Length)
在这里插入图片描述
3.支持断点续传(RangeContent-Rangekoa-range
在这里插入图片描述
4.
在这里插入图片描述

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值