亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Node.js發送文件作為響應

Node.js發送文件作為響應

偶然的你 2019-11-11 14:14:24
Expressjs框架具有sendfile()方法。我如何在不使用整個框架的情況下做到這一點。我正在使用node-native-zip創建檔案,并將其發送給用戶。
查看完整描述

3 回答

?
jeck貓

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 = [文件名]”指定將要下載的文件名。


查看完整回答
反對 回復 2019-11-11
?
holdtom

TA貢獻1805條經驗 獲得超10個贊

“流”是指“在讀取文件數據時將其發送到連接”,而不是“讀取內存中的整個文件然后立即將所有數據發送到該連接”(這是典型的幼稚方法)。我的意思不是?“從內存流式傳輸數據而不將其傳輸到磁盤”。

查看完整回答
反對 回復 2019-11-11
  • 3 回答
  • 0 關注
  • 938 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號