2014-02-05 62 views
2

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

回答

10

您需要設置一些標頭標誌;

res.writeHead(200, { 
    'Content-Type': 'audio/mpeg', 
    'Content-Length': stat.size, 
    'Content-Disposition': 'attachment; filename=your_file_name' 
}); 

用於替換流式下載;

var file = fs.readFile(filePath, 'binary'); 

res.setHeader('Content-Length', stat.size); 
res.setHeader('Content-Type', 'audio/mpeg'); 
res.setHeader('Content-Disposition', 'attachment; filename=your_file_name'); 
res.write(file, 'binary'); 
res.end(); 
+0

感謝它的工作,但現在它只下載4mb的文件,現在整個文件約6mb。 –

+0

你檢查了文件內容嗎?一切都在裏面? –

+4

由於Node.js是單線程的,因此在請求處理程序中用戶'readFileSync'是非常糟糕的。所以如果你對這個URL有兩個請求,那麼第二個請求會等到第一個請求完成它的操作。在本地主機上,您可能沒有注意到任何問題,但是在每秒有1000個請求的生產服務器上,會有延遲。使用['readFile'](http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback)而不是 – Curious

0
response.writeHead(200, { 
    'Content-Type': 'audio/mpeg', 
    modification-date="date_object", 
    'Content-Disposition: attachment; 
    filename=output.mp3' 

    }); 

你需要工作在你的頭部分,即您的內容部署的一部分,只有這樣它可以讓你獲取數據了。閱讀更多關於content Disposition

+0

@MaratArguinbaev - 你有沒有取得任何進展,並使其工作?我知道它是一個古老的線索,但我正在嘗試做類似的事情。還有一個問題是你堅持使用NODE.js還是最終轉向另一個框架/解決方案來實現websockets?謝謝! – tamak

相關問題