你好,我一直在试图从node.js发送文件到客户端。我的代码工作,但是当客户端去指定的网址(/helloworld/hello.js/test)它流文件。从谷歌浏览器访问它使文件(.mp3)在播放器中播放。Node.js发送文件到客户端
我的目标是让客户端的浏览器下载文件并询问客户端在哪里存储它,而不是在网站上流式传输。
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);
});
感谢它的工作,但现在它只下载4mb的文件,现在整个文件约6mb。 –
你检查了文件内容吗?一切都在里面? –
由于Node.js是单线程的,因此在请求处理程序中用户'readFileSync'是非常糟糕的。所以如果你对这个URL有两个请求,那么第二个请求会等到第一个请求完成它的操作。在本地主机上,您可能没有注意到任何问题,但是在每秒有1000个请求的生产服务器上,会有延迟。使用['readFile'](http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback)而不是 – Curious