Something went wrong. Try again.
A Twitter-Bot that is going to increase your followers.
Something went wrong. Try again.
7.1 kB · 234 lines
at master
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235# Form-Data [](https://www.npmjs.com/package/form-data) [](https://gitter.im/form-data/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][xhr2-fd].
[xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface
[](https://travis-ci.org/form-data/form-data)[](https://travis-ci.org/form-data/form-data)[](https://ci.appveyor.com/project/alexindigo/form-data)
[](https://coveralls.io/github/form-data/form-data?branch=master)[](https://david-dm.org/form-data/form-data)[](https://www.bithound.io/github/form-data/form-data)
## 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.
``` javascriptvar FormData = require('form-data');var fs = require('fs');
var form = new FormData();form.append('my_field', 'my value');form.append('my_buffer', new Buffer(10));form.append('my_file', fs.createReadStream('/foo/bar.jpg'));```
Also you can use http-response stream:
``` javascriptvar FormData = require('form-data');var http = require('http');
var form = new FormData();
http.request('http://nodejs.org/images/logo.png', function(response) { form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_logo', response);});```
Or @mikeal's [request](https://github.com/request/request) stream:
``` javascriptvar FormData = require('form-data');var request = require('request');
var form = new FormData();
form.append('my_field', 'my value');form.append('my_buffer', new Buffer(10));form.append('my_logo', request('http://nodejs.org/images/logo.png'));```
In order to submit this form to a web application, call ```submit(url, [callback])``` method:
``` javascriptform.submit('http://example.org/', function(err, res) { // res – response object (http.IncomingMessage) // res.resume();});
```
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`:
``` javascriptvar FormData = require('form-data');
var form = new FormData({ maxDataSize: 20971520 });form.append('my_field', 'my value');form.append('my_buffer', /* something big */);```
List of available options could be found in [combined-stream](https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15)
### Alternative submission methods
You can use node's http client interface:
``` javascriptvar http = require('http');
var request = http.request({ method: 'post', host: 'example.org', path: '/upload', headers: form.getHeaders()});
form.pipe(request);
request.on('response', function(res) { console.log(res.statusCode);});```
Or if you would prefer the `'Content-Length'` header to be set for you:
``` javascriptform.submit('example.org/upload', function(err, res) { console.log(res.statusCode);});```
To use custom headers and pre-known length in parts:
``` javascriptvar CRLF = '\r\n';var form = new FormData();
var options = { header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, knownLength: 1};
form.append('my_buffer', buffer, options);
form.submit('http://example.com/', function(err, res) { if (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:
``` javascriptsomeModule.stream(function(err, stdout, stderr) { if (err) throw err;
var form = new FormData();
form.append('file', stdout, { filename: 'unicycle.jpg', // ... or: filepath: 'photos/toys/unicycle.jpg', contentType: 'image/jpeg', knownLength: 19806 });
form.submit('http://example.com/', function(err, res) { if (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](https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory).
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:
``` javascriptform.submit({ host: '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()`:
``` javascriptform.submit({ host: '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](https://github.com/request/request):
```javascriptvar formData = { my_field: 'my_value', my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),};
request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) { if (err) { return console.error('upload failed:', err); } console.log('Upload successful! Server responded with:', body);});```
For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads).
#### node-fetch
You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch):
```javascriptvar form = new FormData();
form.append('a', 1);
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, use ```knownLength``` options as workaround.- Starting version `2.x` FormData has dropped support for `node@0.10.x`.
## License
Form-Data is released under the [MIT](License) license.