egg.js文件下载实现

多文件合并下载
依赖于 https://github.com/feross/multistream

const streams = [];
for (const file of files) {
  streams.push(fs.createReadStream(file));
}
this.ctx.attachment('filename');
this.ctx.set('Content-Type', 'application/octet-stream');
this.ctx.body = new MultiStream(streams); // new MultiStream(streams).pipe(res)

前端可以浏览器直接访问对应链接,也可以用fetch

fetch(url).then(res => res.blob()).then(blob => {
  let a = document.createElement('a');
  let url = window.URL.createObjectURL(blob);
  a.href = url;
  a.download = `filename.txt`;
  a.click();
  window.URL.revokeObjectURL(url);
  a = null;
});

单文件下载

this.ctx.set('Content-Type', 'application/octet-stream');
this.ctx.body = fs.createReadStream(filePath)

下载字符串内容到文件

this.ctx.set('Content-Type', 'application/octet-stream');
this.ctx.body = str;

推荐阅读: https://www.zhihu.com/question/59351806


最后更新时间: 2021.5.17

原文地址:https://www.cnblogs.com/elimsc/p/14779088.html