本文 介绍了在 eggjs
中如何编写下载模块供其它终端进行文件下载的方法。
Eggjs 官方方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| async index() { this.ctx.body = [ '<a download href="/download">download</a>', '<br>', '<a download href="/download-image">download image</a>', ].join(''); }
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; }
|
支持进度条和剩余时间(Content-Length)
为了支持进度条,需要在 HTTP 返回头里设置
Content-Length
1 2 3 4 5 6 7 8 9 10 11 12 13
| const fs = require('fs') const util = require('util')
...
async download() { const filePath = '/path/to/file'; const fileSize = (await util.promisify(fs.stat)(filePath)).size.toString(); this.ctx.attachment(filePath); this.ctx.set('Content-Length', fileSize); this.ctx.set('Content-Type', 'application/octet-stream'); this.ctx.body = fs.createReadStream(filePath); }
|
分段下载
未完成。
参考
- https://github.com/eggjs/examples/blob/master/download/app/controller/index.js
- eggjs怎么实现文件下载?