Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

A module to create readable `"multipart/form-data"` streams. Can be used to submit forms and file uploads to other web applications.

License

NotificationsYou must be signed in to change notification settings

form-data/form-data

Repository files navigation

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 theXMLHttpRequest-2 FormData Interface.

Linux BuildMacOS BuildWindows Build

Coverage StatusDependency Status

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.

varFormData=require('form-data');varfs=require('fs');varform=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:

varFormData=require('form-data');varhttp=require('http');varform=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);});

Or @mikeal'srequest stream:

varFormData=require('form-data');varrequest=require('request');varform=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, callsubmit(url, [callback]) method:

form.submit('http://example.org/',function(err,res){// res – response object (http.IncomingMessage)  //res.resume();});

For more advanced request manipulationssubmit() method returnshttp.ClientRequest object, or you can choose from one of the alternative submission methods.

Custom options

You can provide custom options, such asmaxDataSize:

varFormData=require('form-data');varform=newFormData({maxDataSize:20971520});form.append('my_field','my value');form.append('my_buffer',/* something big */);

List of available options could be found incombined-stream

Alternative submission methods

You can use node's http client interface:

varhttp=require('http');varrequest=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:

form.submit('example.org/upload',function(err,res){console.log(res.statusCode);});

To use custom headers and pre-known length in parts:

varCRLF='\r\n';varform=newFormData();varoptions={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)throwerr;console.log('Done');});

Form-Data can recognize and fetch all the required information from common types of streams (fs.readStream,http.response andmikeal's request), for some other types of streams you'd need to provide "file"-related information manually:

someModule.stream(function(err,stdout,stderr){if(err)throwerr;varform=newFormData();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)throwerr;console.log('Done');});});

Thefilepath property overridesfilename and may contain a relative path. This is typically used when uploadingmultiple 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 toform.submit() as first parameter:

form.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 theheaders key in first parameter ofform.submit():

form.submit({host:'example.com',path:'/surelynot.php',headers:{'x-test-header':'test-header-value'}},function(err,res){console.log(res.statusCode);});

Methods

Void append(Stringfield,Mixedvalue [,Mixedoptions] )

Append data to the form. You can submit about any format (string, integer, boolean, buffer, etc.). However, Arrays are not supported and need to be turned into strings by the user.

varform=newFormData();form.append('my_string','my value');form.append('my_integer',1);form.append('my_boolean',true);form.append('my_buffer',newBuffer(10));form.append('my_array_as_json',JSON.stringify(['bird','cute']))

You may provide a string for options, or an object.

// Set filename by providing a string for optionsform.append('my_file',fs.createReadStream('/foo/bar.jpg'),'bar.jpg');// provide an object.form.append('my_file',fs.createReadStream('/foo/bar.jpg'),{filename:'bar.jpg',contentType:'image/jpeg',knownLength:19806});

Headers getHeaders( [HeadersuserHeaders] )

This method adds the correctcontent-type header to the provided array ofuserHeaders.

String getBoundary()

Return the boundary of the formData. By default, the boundary consists of 26- followed by 24 numbersfor example:

--------------------------515890814546601021194782

Void setBoundary(Stringboundary)

Set the boundary string, overriding the default behavior described above.

Note: The boundary must be unique and may not appear in the data.

Buffer getBuffer()

Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data.

varform=newFormData();form.append('my_buffer',Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]));form.append('my_file',fs.readFileSync('/foo/bar.jpg'));axios.post('https://example.com/path/to/api',form.getBuffer(),form.getHeaders())

Note: Because the output is of type Buffer, you can only append types that are accepted by Buffer:string, Buffer, ArrayBuffer, Array, or Array-like Object. A ReadStream for example will result in an error.

Integer getLengthSync()

Same asgetLength but synchronous.

Note: getLengthSyncdoesn't calculate streams length.

Integer getLength(functioncallback )

Returns theContent-Length async. The callback is used to handle errors and continue once the length has been calculated

this.getLength(function(err,length){if(err){this._error(err);return;}// add content lengthrequest.setHeader('Content-Length',length);  ...}.bind(this));

Boolean hasKnownLength()

Checks if the length of added values is known.

Request submit(params,functioncallback )

Submit the form to a web application.

varform=newFormData();form.append('my_string','Hello World');form.submit('http://example.com/',function(err,res){// res – response object (http.IncomingMessage)  //res.resume();});

String toString()

Returns the form data as a string. Don't use this if you are sending files or buffers, usegetBuffer() instead.

Integration with other libraries

Request

Form submission usingrequest:

varformData={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){returnconsole.error('upload failed:',err);}console.log('Upload successful!  Server responded with:',body);});

For more details seerequest readme.

node-fetch

You can also submit a form usingnode-fetch:

varform=newFormData();form.append('a',1);fetch('http://example.com',{method:'POST',body:form}).then(function(res){returnres.json();}).then(function(json){console.log(json);});

axios

In Node.js you can post a file usingaxios:

constform=newFormData();conststream=fs.createReadStream(PATH_TO_FILE);form.append('image',stream);// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`constformHeaders=form.getHeaders();axios.post('http://example.com',form,{headers:{    ...formHeaders,},}).then(response=>response).catch(error=>error)

Notes

  • getLengthSync() method DOESN'T calculate length for streams, useknownLength options as workaround.
  • getLength(cb) will send an error as first parameter of callback if stream length cannot be calculated (e.g. send in custom streams w/o usingknownLength).
  • submit will not addcontent-length if form length is unknown or not calculable.
  • Starting version2.x FormData has dropped support fornode@0.10.x.
  • Starting version3.x FormData has dropped support fornode@4.x.

License

Form-Data is released under theMIT license.

About

A module to create readable `"multipart/form-data"` streams. Can be used to submit forms and file uploads to other web applications.

Topics

Resources

License

Stars

Watchers

Forks


[8]ページ先頭

©2009-2025 Movatter.jp