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);
});
複製代碼