Expressjs框架有一個sendfile()方法。我怎麼做,而不使用整個框架。我正在使用node-native-zip創建一個存檔,並且我想將其發送給用戶。Nodejs發送文件作爲響應
75
A
回答
119
下面是一個示例程序,它將通過從磁盤流式傳輸myfile.mp3(即,在發送文件之前不會將整個文件讀入內存)。服務器監聽端口2000
[更新]作爲評價提及@Aftershock,util.pump
消失,並與稱爲pipe
的流原型的方法代替;下面的代碼反映了這一點。
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.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.pipe(response);
})
.listen(2000);
從http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/
3
您需要使用流以響應發送文件(檔案)拍攝的,更重要的是你有你的響應頭使用適當的內容類型。
有一個例子函數,做到這一點:
const fs = require('fs');
// Where fileName is name of the file and response is Node.js Reponse.
responseFile = (fileName, response) => {
const filePath = "/path/to/archive.rar" // or any file format
// Check if file specified by the filePath exists
fs.exists(filePath, function(exists){
if (exists) {
// Content-type is very interesting part that guarantee that
// Web browser will handle response in an appropriate manner.
response.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition": "attachment; filename=" + fileName
});
fs.createReadStream(filePath).pipe(response);
} else {
response.writeHead(400, {"Content-Type": "text/plain"});
response.end("ERROR File does not exist");
}
});
}
}
在Content-Type字段的目的是描述包含在該人體完全足夠的是,接收用戶代理可以選擇一個合適的數據代理或機制向用戶呈現數據,或者以適當的方式處理數據。
「應用程序/八位字節流」在RFC 2046中定義爲「任意的二進制數據」,這種內容類型的目的是爲了保存到磁盤 - 什麼是你真正需要的。
「文件名= [文件名]」指定將被下載的文件的名稱。請參閱this stackoverflow topic。
相關問題
- 1. Nodejs發送部分響應
- 2. NodeJS響應不發送index.html
- 3. 發送來自NodeJS/Express的JSON響應
- 4. 發送Office Open XML文件作爲響應
- 5. Nodejs Express發送文件
- 6. 發送XML字符串作爲響應
- 7. Nodejs發送部分響應不起作用
- 8. CakePHP響應發送爲空
- 9. Turbogears響應 - 發送utf-8文件名
- 10. 如何發送發送狀態代碼作爲404響應而不是404.jsp作爲html響應在春季?
- 11. 的XMLHttpRequest發送URL作爲響應文本,Firefox不重定向
- 12. 發送502響應:應用程序未發送完整響應
- 13. 發送json響應
- 14. 如何發送一個文件作爲節點js中的響應下載
- 15. 如何將文件NodeJS發送給java
- 16. Nodejs通過http發送文件
- 17. 發送大JSON對象作爲響應是發生在快遞
- 18. 發送壓縮文件作爲附件
- 19. 作爲附件發送多個文件
- 20. Azure函數 - NodeJS - 響應正文作爲流
- 21. Nodejs向JIRA發送附件
- 22. 向nodejs中的客戶端發送響應
- 23. 使用python-shell發送多個來自nodejs的響應
- 24. 發送的NodeJS XHR響應不可用客戶端
- 25. 無法發送文件作出迴應
- 26. NodeJS - 響應流
- 27. 發送請求作爲jsonp,將響應解釋爲文本,使用jQuery 1.5
- 28. 作爲excel文件下載響應
- 29. 作爲文件的WebApi下載響應
- 30. Laravel響應發送android應用程序文件
但我沒有從服務器上流式傳輸文件,我創建了存檔文件 – andrei 2012-04-06 21:32:25
「流」我的意思是「發送文件數據到連接,因爲它正在讀取」,而不是「讀取內存中的整個文件,然後一次發送所有數據到連接「(這是典型的天真方法)。我並不是指「將內存中的數據流到磁盤中。」我鏈接的帖子更詳細地解釋了。 – 2012-04-06 22:57:45
好吧,現在我明白了,謝謝。我會從那裏開始 – andrei 2012-04-08 08:56:39