7.0 KiB
Form-Data
A library to create readable "multipart/form-data"
streams. Can be used to submit forms and file uploads to other web
applications.
The API of this library is inspired by the XMLHttpRequest-2 FormData Interface.
Install
npm install --save form-data
Usage
In this example we are constructing a form with 3 fields that contain a string, a buffer and a file stream.
var FormData = require('form-data');
var fs = require('fs');
var form = new FormData();
.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg')); form
Also you can use http-response stream:
var FormData = require('form-data');
var http = require('http');
var form = new FormData();
.request('http://nodejs.org/images/logo.png', function(response) {
http.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_logo', response);
form; })
Or @mikeal’s request stream:
var FormData = require('form-data');
var request = require('request');
var form = new FormData();
.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_logo', request('http://nodejs.org/images/logo.png')); form
In order to submit this form to a web application, call
submit(url, [callback])
method:
.submit('http://example.org/', function(err, res) {
form// res – response object (http.IncomingMessage) //
.resume();
res; })
For more advanced request manipulations submit()
method
returns http.ClientRequest
object, or you can choose from
one of the alternative submission methods.
Custom options
You can provide custom options, such as maxDataSize
:
var FormData = require('form-data');
var form = new FormData({ maxDataSize: 20971520 });
.append('my_field', 'my value');
form.append('my_buffer', /* something big */); form
List of available options could be found in combined-stream
Alternative submission methods
You can use node’s http client interface:
var http = require('http');
var request = http.request({
method: 'post',
host: 'example.org',
path: '/upload',
headers: form.getHeaders()
;
})
.pipe(request);
form
.on('response', function(res) {
requestconsole.log(res.statusCode);
; })
Or if you would prefer the 'Content-Length'
header to be
set for you:
.submit('example.org/upload', function(err, res) {
formconsole.log(res.statusCode);
; })
To use custom headers and pre-known length in parts:
var CRLF = '\r\n';
var form = new FormData();
var options = {
header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF,
knownLength: 1
;
}
.append('my_buffer', buffer, options);
form
.submit('http://example.com/', function(err, res) {
formif (err) throw err;
console.log('Done');
; })
Form-Data can recognize and fetch all the required information from
common types of streams (fs.readStream
,
http.response
and mikeal's request
), for some
other types of streams you’d need to provide “file”-related information
manually:
.stream(function(err, stdout, stderr) {
someModuleif (err) throw err;
var form = new FormData();
.append('file', stdout, {
formfilename: 'unicycle.jpg', // ... or:
filepath: 'photos/toys/unicycle.jpg',
contentType: 'image/jpeg',
knownLength: 19806
;
})
.submit('http://example.com/', function(err, res) {
formif (err) throw err;
console.log('Done');
;
}); })
The filepath
property overrides filename
and may contain a relative path. This is typically used when uploading
multiple
files from a directory.
For edge cases, like POST request to URL with query string or to pass
HTTP auth credentials, object can be passed to
form.submit()
as first parameter:
.submit({
formhost: 'example.com',
path: '/probably.php?extra=params',
auth: 'username:password'
, function(err, res) {
}console.log(res.statusCode);
; })
In case you need to also send custom HTTP headers with the POST
request, you can use the headers
key in first parameter of
form.submit()
:
.submit({
formhost: 'example.com',
path: '/surelynot.php',
headers: {'x-test-header': 'test-header-value'}
, function(err, res) {
}console.log(res.statusCode);
; })
Integration with other libraries
Request
Form submission using request:
var formData = {
my_field: 'my_value',
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
;
}
.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
requestif (err) {
return console.error('upload failed:', err);
}console.log('Upload successful! Server responded with:', body);
; })
For more details see request readme.
node-fetch
You can also submit a form using node-fetch:
var form = new FormData();
.append('a', 1);
form
fetch('http://example.com', { method: 'POST', body: form })
.then(function(res) {
return res.json();
.then(function(json) {
})console.log(json);
; })
Notes
getLengthSync()
method DOESN’T calculate length for streams, useknownLength
options as workaround.- Starting version
2.x
FormData has dropped support fornode@0.10.x
.
License
Form-Data is released under the MIT license.