前后端处理流文件请求

2,915 阅读1分钟

知识点

  • nodeAPI——stream
  • nodeAPI——fs
  • koa——response封装

服务端返回流文件

koa 请求响应流文件

this.ctx.body = fs.createReadStream(`${__dirname}/../../index.js`);

koa/lib/application.js 源码中,有判断body是否为流对象,然后 pipe 到响应对象中去

// responses
  if (Buffer.isBuffer(body)) return res.end(body);
  if ('string' == typeof body) return res.end(body);
  if (body instanceof Stream) return body.pipe(res);

前端处理流文件

引用fetch库,response为ReadableStream对象,blob() 后可获取buffer文件。利用h5的URL的API来下载buffer文件

import fetch from 'dva/fetch';
fetch(`http://localhost:7001/test`, {method: 'GET',})
.then((res) => res.blob())
.then((blob)=>{
  var a = document.createElement("a");
  const url = window.URL || window.webkitURL || window.moxURL
  // 创建下载链接
  a.href = url.createObjectURL(blob)
  a.download = "a.txt";
  document.body.appendChild(a);
  a.click();
  // 然后移除
  document.body.removeChild(a);
});