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