在服务端处理文件下载时,其实操作起来并不复杂,只有两步就可以完成下载操作。
第一步:设置响应头
const header = { 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment;filename=req_get_download.js'};
上面是 nodejs 中的写法,其实不管哪种语言,只要注意设置响应头中的 Content-Type
和 Content-Disposition
属性即可,响应头 header 无关编程语言,是通用的。
-
'Content-Type': 'application/octet-stream'
表明这是一个二进制文件
-
'Content-Disposition': 'attachment;filename=req_get_download.js'
表明这是一个需要下载的附件并告诉浏览器默认文件名
第二步:返回数据流
读取要下载的文件,以二进制流的形式响应给客户端
node 中完整写法
fs.readFile('./req_get_download.js', function (err, data) { const header = { 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment;filename=req_get_download.js' }; res.writeHead(200, header); res.end(data);});