先后端处理流文件请求

知识点

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

服务端返回流文件

koa 请求响应流文件前端

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

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

// 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文件web

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);
});
复制代码
相关文章
相关标签/搜索