- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements