egg 实现下载

egg 最简单的下载实现如下:

async download(){
  const { ctx } = this;
  const filePath = '/path/xml'
  ctx.attachment('xml');
  ctx.set('Content-Type','application/octet-stream');
  ctx.boby = fs.createReadStream(filePath)
}

加入 Content-Length 支持进度条和剩余时间
仅需这样实现,即可实现下载,但这样实现的下载会发现没有下载进度条,也不知道还有多久下载完。原因 HTTP 返回头里没有 Content-Length

async download(){
  const { ctx } = this;
  const filePath = '/path/xml'
  const fileSize = (await promisify(stat)(filePath)).size.toString()
  ctx.attachment('xml');
  ctx.set('Content-Length', fileSize);
  ctx.set('Content-Type','application/octet-stream');
  ctx.boby = fs.createReadStream(filePath)
}

加入 Range 和 Content-Range - 支持断点续传
但这还不够,我还希望能支持断点续传,这个时候我们就需要了解一下 Range 和 Content-Range了。也就是说,在服务端我们需要处理客户端请求头中的 Range 字段,同时再返回 Content-Range。

当然这样的需求肯定有人造了轮子了,没必要自己实现。我没有找到 egg 生态的轮子,但我找到了
koa 生态中有一个中间件叫 koa-range,我们可以拿过来用。

先创建一个中间件

import * as KoaRange from 'koa-range';
export default function RangeMiddleware() {
  return KoaRange;
}

然后在配置中启用它:

import { EggAppConfig, EggAppInfo, PowerPartial } from 'egg
export default (appInfo: EggAppInfo) => {
 const config = {} as PowerPartial<EggAppConfig>;
 config.middleware = ['range'];
 return config;
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值