res.attachment() 方法在 Express.js
res.attachment() 方法用於將 Content-Disposition 標頭欄位設定為 “attachment”。如果傳遞了檔名,則它會基於從 res.type() 獲取的副檔名設定 Content-type。它使用引數設定 Content-Disposition 的 “filename” 欄位。
語法
res.attachment()
示例 1
建立一個名為 “resAttachment.js” 的檔案並複製以下程式碼片段。建立檔案後,使用 “node resAttachment.js” 命令執行此程式碼,如下例所示 −
// res.attachment() Method Demo Example
// Importing the express
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Defining an endpoint
app.get('/api', function(req, res){
res.attachment('attacment.txt');
console.log(res.get('Content-Disposition'));
res.end();
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 請求訪問以下端點 − localhost:3000/api
輸出
C:\home
ode>> node resAttachment.js Server listening on PORT 3000 attachment; filename="attacment.txt"
示例 2
我們來看另一個示例。
// res.attachment() Method Demo Example
// Importing the express
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Defining an endpoint
// With middleware
app.use('/api', function(req, res, next){
res.attachment('tutorialspoint.txt');
console.log(res.get('Content-Disposition'));
next();
})
app.get('/api', function(req, res){
console.log('Attachment Added');
res.send("Attachment Added");
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 請求訪問以下端點 − localhost:3000/api
輸出
C:\home
ode>> node resAttachment.js Server listening on PORT 3000 attachment; filename="tutorialspoint.txt" Attachment Added
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP