你好,我一直在試圖從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