如题,有时我们需要在后端创建一个可下载文件的 URL,在 NodeJS 中实现如下:
// The must headers.
res.setHeader('Content-type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment;filename=aaa.txt'); // 'aaa.txt' can be customized.
var fileStream = fs.createReadStream('./download/aaa.txt');
fileStream.on('data', function (data) {
res.write(data, 'binary');
});
fileStream.on('end', function () {
res.end();
});
以上代码中,主要有以下两步:
(1)设置响应消息头部
(2)创建可读数据流,读取数据时将数据写入响应消息中
可运行 Demo 见:https://github.com/nanzhangren/download_file