在原来代码中发现一个接口,直接使用url就可以下载文件,没有特殊的地方,
研究了一下,原来是靠响应头实现的。
// server.js
const http = require('http');
function middleware(req,res){
// 核心,因为使用location.href = url,所以设置window-Target,
res.setHeader('window-Target','_blank');
// 核心,filename 还可以使用 filename*
res.setHeader('content-Disposition','attachment;filename=test.html');
// 很简单,这就完成了
res.end('<html><h1>hello</h1></html>');
}
http.createServer(middleware).listen(8080);
// index.html
// <button onclick="window.location.href = 'http://localhost:8080'">download</button>
// 或者打开控制台
window.location.href = 'http://localhost:8080'
没想到以前还有这种技术~
window-Target,还没找到文档