3 回答

TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
您需要使用Stream在響應(yīng)中發(fā)送文件(存檔),此外,您還必須在響應(yīng)頭中使用適當(dāng)?shù)腃ontent-type。
有一個(gè)執(zhí)行此操作的示例函數(shù):
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字段的目的是充分描述主體中包含的數(shù)據(jù),以使接收用戶的代理可以選擇適當(dāng)?shù)拇砘驒C(jī)制,以將數(shù)據(jù)呈現(xiàn)給用戶,或者以適當(dāng)?shù)姆绞教幚頂?shù)據(jù)。
“應(yīng)用程序/八位字節(jié)流”在RFC 2046中定義為“任意二進(jìn)制數(shù)據(jù)”,此內(nèi)容類型的目的是保存到磁盤-這是您真正需要的。
“ filename = [文件名]”指定將要下載的文件名。

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
“流”是指“在讀取文件數(shù)據(jù)時(shí)將其發(fā)送到連接”,而不是“讀取內(nèi)存中的整個(gè)文件然后立即將所有數(shù)據(jù)發(fā)送到該連接”(這是典型的幼稚方法)。我的意思不是?“從內(nèi)存流式傳輸數(shù)據(jù)而不將其傳輸?shù)酱疟P”。
- 3 回答
- 0 關(guān)注
- 933 瀏覽
添加回答
舉報(bào)