當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Express.js res.attachment()用法及代碼示例

res.attachment()函數用於將HTTP響應Content-Disposition標頭字段設置為‘attachment’。如果文件名以文件名形式給出,則它將通過res.type()函數根據擴展名設置Content-Type,最後設置Content-Disposition“ filename =”參數。

用法:

res.attachment( [filename] )

參數:filename參數描述文件的名稱。

返回值:它重新調整對象。

快遞模塊的安裝:



  1. 您可以訪問安裝Express模塊​​的鏈接。您可以使用此命令安裝此軟件包。
    npm install express
  2. 安裝Express模塊​​後,可以使用命令在命令提示符下檢查Express版本。
    npm version express
  3. 之後,您可以僅創建一個文件夾並添加一個文件,例如index.js。要運行此文件,您需要運行以下命令。
    node index.js

範例1: 文件名:index.js

var express = require('express'); 
var app = express(); 
var PORT = 3000; 
  
// Without middleware 
app.get('/', function(req, res){ 
    res.attachment('Hello.txt'); 
    console.log(res.get('Content-Disposition'));  
}); 
  
app.listen(PORT, function(err){ 
    if (err) console.log(err); 
    console.log("Server listening on PORT", PORT); 
});

將任何文件放在可以附加的項目的根目錄中,就像這裏我們使用Hello.txt一樣。

運行程序的步驟:

  1. 項目結構將如下所示:
  2. 確保使用以下命令安裝了Express模塊​​:
    npm install express
  3. 使用以下命令運行index.js文件:
    node index.js

    輸出:

    Server listening on PORT 3000
    
  4. 打開瀏覽器並轉到http://localhost:3000 /,現在您可以在控製台上看到以下輸出:
    Server listening on PORT 3000
    attachment; filename="Hello.txt"
    
  5. 範例2: 文件名:index.js

    var express = require('express'); 
    var app = express(); 
    var PORT = 3000; 
      
    // With middleware 
    app.use('/', function(req, res, next){ 
        res.attachment('GFG.txt'); 
        console.log(res.get('Content-Disposition'));  
        next(); 
    }) 
      
    app.get('/', function(req, res){ 
        console.log('Attachment Added');  
        res.send(); 
    }); 
      
    app.listen(PORT, function(err){ 
        if (err) console.log(err); 
        console.log("Server listening on PORT", PORT); 
    });

    使用以下命令運行index.js文件:

    node index.js

    打開瀏覽器並轉到http://localhost:3000 /,現在您可以在控製台上看到以下輸出:

    Server listening on PORT 3000
    attachment; filename="GFG.txt"
    Attachment Added
    

    參考: https://expressjs.com/en/5x/api.html#res.attachment




相關用法


注:本文由純淨天空篩選整理自gouravhammad大神的英文原創作品 Express.js res.attachment() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。