先後端處理流文件請求

知識點

  • 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);
});
複製代碼
相關文章
相關標籤/搜索