【发布时间】:2014-03-01 22:34:29
【问题描述】:
您好,我一直在尝试将文件从 node.js 发送到客户端。
我的代码可以工作,但是当客户端转到指定的 url (/helloworld/hello.js/test) 时,它会流式传输文件。
从 Google Chrome 访问它会使文件 (.mp3) 在播放器中播放。
我的目标是让客户的浏览器下载文件并询问客户他想将它存储在哪里,而不是在网站上流式传输。
http.createServer(function(req, res) {
switch (req.url) {
case '/helloworld/hello.js/test':
var filePath = path.join(__dirname, '/files/output.mp3');
var stat = fileSystem.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.on('open', function() {
// This just pipes the read stream to the response object (which goes to the client)
readStream.pipe(res);
});
readStream.on('error', function(err) {
res.end(err);
});
}
});
【问题讨论】:
标签: javascript html node.js