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 =newFormData();form.append('my_field','my value');form.append('my_buffer',newBuffer(10));form.append('my_file',fs.createReadStream('/foo/bar.jpg'));
Also you can use http-response stream:
var FormData =require('form-data');var http =require('http');var form =newFormData();http.request('http://nodejs.org/images/logo.png',function(response) {form.append('my_field','my value');form.append('my_buffer',newBuffer(10));form.append('my_logo', response);});
var FormData =require('form-data');var request =require('request');var form =newFormData();form.append('my_field','my value');form.append('my_buffer',newBuffer(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:
form.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:
var FormData =require('form-data');var form =newFormData({ maxDataSize:20971520 });form.append('my_field','my value');form.append('my_buffer',/* something big */);
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:
var form =newFormData();form.append('a',1);fetch('http://example.com', { method:'POST', body: form }).then(function(res) {returnres.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.