Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
multiparty
Advanced tools
The multiparty npm package is a node.js module for parsing multipart/form-data, which is primarily used for handling file uploads. It can parse incoming request bodies in a middleware-like fashion, making it easier to handle file uploads and form data in web applications.
Parsing Form Data
This feature allows you to parse form data from a POST request. The code sample demonstrates how to create an HTTP server that listens for POST requests, parses the form data using multiparty, and responds with the parsed fields and files in JSON format.
const multiparty = require('multiparty');
const http = require('http');
http.createServer((req, res) => {
if (req.method === 'POST') {
const form = new multiparty.Form();
form.parse(req, (err, fields, files) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error parsing form data');
return;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ fields, files }));
});
} else {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Method Not Allowed');
}
}).listen(8080);
Handling File Uploads
This feature allows you to handle file uploads. The code sample demonstrates how to create an HTTP server that listens for POST requests, parses the uploaded file using multiparty, and saves it to a specified directory.
const multiparty = require('multiparty');
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
if (req.method === 'POST') {
const form = new multiparty.Form();
form.parse(req, (err, fields, files) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error parsing form data');
return;
}
const file = files.upload[0];
const tempPath = file.path;
const targetPath = './uploads/' + file.originalFilename;
fs.rename(tempPath, targetPath, (err) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error saving file');
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('File uploaded successfully');
});
});
} else {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Method Not Allowed');
}
}).listen(8080);
Formidable is another Node.js module for parsing form data, especially file uploads. It is similar to multiparty in functionality but is known for its performance and simplicity. Formidable provides a more straightforward API for handling file uploads and form data parsing.
Busboy is a Node.js module for parsing incoming HTML form data. It is built on streams and is highly efficient for handling large file uploads. Compared to multiparty, Busboy is more performant and is often preferred for high-performance applications.
Multer is a middleware for handling multipart/form-data, which is primarily used for uploading files. It is built on top of Busboy and provides an easy-to-use API for handling file uploads in Express applications. Multer is more feature-rich and integrates seamlessly with Express, making it a popular choice for Express-based applications.
Parse http requests with content-type multipart/form-data
, also known as file uploads.
Content-Length
of
each part.npm install multiparty
Parse an incoming multipart/form-data
request.
var multiparty = require('multiparty')
, http = require('http')
, util = require('util')
http.createServer(function(req, res) {
if (req.url === '/upload' && req.method === 'POST') {
// parse a file upload
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8080);
var form = new multiparty.Form(options)
Creates a new form. Options:
encoding
- sets encoding for the incoming form fields. Defaults to utf8
.maxFieldSize
- Limits the amount of memory a field (not a file) can
allocate in bytes. If this value is exceeded, an error
event is emitted.
The default size is 2MB.maxFields
- Limits the number of fields that will be parsed before
emitting an error
event. A file counts as a field in this case.
Defaults to 1000.autoFields
- Enables field
events. This is automatically set to true
if you add a field
listener.autoFiles
- Enables file
events. This is automatically set to true
if you add a file
listener.uploadDir
- Only relevant when autoFiles
is true
. The directory for
placing file uploads in. You can move them later using fs.rename()
.
Defaults to os.tmpDir()
.hash
- Only relevant when autoFiles
is true
. If you want checksums
calculated for incoming files, set this to either sha1
or md5
.
Defaults to off.Parses an incoming node.js request
containing form data. If cb
is
provided, autoFields
and autoFiles
are set to true
and all fields and
files are collected and passed to the callback:
form.parse(req, function(err, fields, files) {
// ...
});
The amount of bytes received for this form so far.
The expected number of bytes in this form.
You definitely want to handle this event. If not your server will crash when users submit bogus multipart requests!
Emitted when a part is encountered in the request. part
is a
ReadableStream
. It also has the following properties:
headers
- the headers for this part. For example, you may be interested
in content-type
.name
- the field name for this partfilename
- only if the part is an incoming filebyteOffset
- the byte offset of this part in the request bodybyteCount
- assuming that this is the last part in the request,
this is the size of this part in bytes. You could use this, for
example, to set the Content-Length
header if uploading to S3.
If the part had a Content-Length
header then that value is used
here instead.Emitted when the request is aborted. This event will be followed shortly
by an error
event. In practice you do not need to handle this event.
Emitted after all parts have been parsed and emitted. Not emitted if an error
event is emitted. This is typically when you would send your response.
By default multiparty will not touch your hard drive. But if you add this
listener, multiparty automatically sets form.autoFiles
to true
and will
stream uploads to disk for you.
name
- the field name for this filefile
- an object with these properties:
originalFilename
- the filename that the user reports for the filepath
- the absolute path of the uploaded file on diskheaders
- the HTTP headers that were sent along with this filesize
- size of the file in bytesIf you set the form.hash
option, then file
will also contain a hash
property which is the checksum of the file.
name
- field namevalue
- string field valueFAQs
multipart/form-data parser which supports streaming
The npm package multiparty receives a total of 476,930 weekly downloads. As such, multiparty popularity was classified as popular.
We found that multiparty demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.