参考文章
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.支持断点续传(Range和Content-Range)koa-range
4.