res.attachment() Method in Express.js


The res.attachment() method is used for setting the Content-Disposition header field to "attachment". If a filename is passed, then it sets the Content-type based on the extension name that is retrieved from the res.type(). It sets the Content-Disposition "filename" field with the parameter.

Syntax

res.attachment()

Example 1

Create a file with the name "resAttachment.js" and copy the following code snippet. After creating the file, use the command "node resAttachment.js" to run this code as shown in the example below −

// 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);
});

Hit the following Endpoint with a GET request − localhost:3000/api

Output

C:\home
ode>> node resAttachment.js Server listening on PORT 3000 attachment; filename="attacment.txt"

Example 2

Let's take a look at one more example.

// 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);
});

Hit the following Endpoint with a GET Request − localhost:3000/api

Output

C:\home
ode>> node resAttachment.js Server listening on PORT 3000 attachment; filename="tutorialspoint.txt" Attachment Added

Updated on: 29-Jan-2022

892 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements