3 回答

TA貢獻1909條經驗 獲得超7個贊
您需要使用Stream在響應中發送文件(存檔),此外,您還必須在響應頭中使用適當的Content-type。
有一個執行此操作的示例函數:
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中定義為“任意二進制數據”,此內容類型的目的是保存到磁盤-這是您真正需要的。
“ filename = [文件名]”指定將要下載的文件名。

TA貢獻1805條經驗 獲得超10個贊
“流”是指“在讀取文件數據時將其發送到連接”,而不是“讀取內存中的整個文件然后立即將所有數據發送到該連接”(這是典型的幼稚方法)。我的意思不是?“從內存流式傳輸數據而不將其傳輸到磁盤”。
- 3 回答
- 0 關注
- 938 瀏覽
添加回答
舉報