What is content-disposition?
The content-disposition npm package is used to create and parse HTTP Content-Disposition headers. It is commonly used to set the disposition type (inline or attachment) and parameters for a response in a web application, which instructs the browser how to handle the content, such as to display it inline or to download it as a file.
What are content-disposition's main functionalities?
Creating Content-Disposition header for attachment
This code sample demonstrates how to create a Content-Disposition header for an attachment, suggesting the browser to download the file as 'filename.txt'.
const contentDisposition = require('content-disposition');
let header = contentDisposition('filename.txt');
Creating Content-Disposition header with Unicode filenames
This code sample shows how to create a Content-Disposition header for a file with a Unicode filename, ensuring proper encoding for non-ASCII characters.
const contentDisposition = require('content-disposition');
let header = contentDisposition('filename.txt', { type: 'attachment', filename: 'файл.txt' });
Parsing Content-Disposition header
This code sample illustrates how to parse a Content-Disposition header string to get an object representing the disposition type and parameters.
const contentDisposition = require('content-disposition');
let parsedHeader = contentDisposition.parse('attachment; filename="filename.txt"');
Other packages similar to content-disposition
mime
The 'mime' package can be used to determine a file's MIME type based on its extension, which is helpful when setting the Content-Type header. It does not directly handle Content-Disposition headers but is often used in conjunction with setting these headers.
form-data
The 'form-data' package allows for the creation and submission of FormData instances, which can include files with specific Content-Disposition. It is more focused on constructing multipart/form-data payloads than on creating or parsing Content-Disposition headers.
content-disposition
Create an attachment Content-Disposition header
Installation
$ npm install content-disposition
API
var contentDisposition = require('content-disposition')
contentDisposition([filename])
Create an attachment Content-Disposition
header value using the given file name,
if supplied.
res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf'))
Examples
Send a file for download
var contentDisposition = require('content-disposition')
var destroy = require('destroy')
var http = require('http')
var onFinished = require('on-finished')
var filePath = '/path/to/public/plans.pdf'
http.createServer(function onRequest(req, res) {
res.setHeader('Content-Type', 'application/pdf')
res.setHeader('Content-Disposition', contentDisposition(filePath))
var stream = fs.createReadStream(filePath)
stream.pipe(res)
onFinished(res, function (err) {
destroy(stream)
})
})
Testing
$ npm test
References
License
MIT