README.md.bak 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. # Form-Data [![NPM Module](https://img.shields.io/npm/v/form-data.svg)](https://www.npmjs.com/package/form-data) [![Join the chat at https://gitter.im/form-data/form-data](http://form-data.github.io/images/gitterbadge.svg)](https://gitter.im/form-data/form-data)
  2. A library to create readable ```"multipart/form-data"``` streams. Can be used to submit forms and file uploads to other web applications.
  3. The API of this library is inspired by the [XMLHttpRequest-2 FormData Interface][xhr2-fd].
  4. [xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface
  5. [![Linux Build](https://img.shields.io/travis/form-data/form-data/v3.0.1.svg?label=linux:6.x-12.x)](https://travis-ci.org/form-data/form-data)
  6. [![MacOS Build](https://img.shields.io/travis/form-data/form-data/v3.0.1.svg?label=macos:6.x-12.x)](https://travis-ci.org/form-data/form-data)
  7. [![Windows Build](https://img.shields.io/travis/form-data/form-data/v3.0.1.svg?label=windows:6.x-12.x)](https://travis-ci.org/form-data/form-data)
  8. [![Coverage Status](https://img.shields.io/coveralls/form-data/form-data/v3.0.1.svg?label=code+coverage)](https://coveralls.io/github/form-data/form-data?branch=master)
  9. [![Dependency Status](https://img.shields.io/david/form-data/form-data.svg)](https://david-dm.org/form-data/form-data)
  10. ## Install
  11. ```
  12. npm install --save form-data
  13. ```
  14. ## Usage
  15. In this example we are constructing a form with 3 fields that contain a string,
  16. a buffer and a file stream.
  17. ``` javascript
  18. var FormData = require('form-data');
  19. var fs = require('fs');
  20. var form = new FormData();
  21. form.append('my_field', 'my value');
  22. form.append('my_buffer', new Buffer(10));
  23. form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
  24. ```
  25. Also you can use http-response stream:
  26. ``` javascript
  27. var FormData = require('form-data');
  28. var http = require('http');
  29. var form = new FormData();
  30. http.request('http://nodejs.org/images/logo.png', function(response) {
  31. form.append('my_field', 'my value');
  32. form.append('my_buffer', new Buffer(10));
  33. form.append('my_logo', response);
  34. });
  35. ```
  36. Or @mikeal's [request](https://github.com/request/request) stream:
  37. ``` javascript
  38. var FormData = require('form-data');
  39. var request = require('request');
  40. var form = new FormData();
  41. form.append('my_field', 'my value');
  42. form.append('my_buffer', new Buffer(10));
  43. form.append('my_logo', request('http://nodejs.org/images/logo.png'));
  44. ```
  45. In order to submit this form to a web application, call ```submit(url, [callback])``` method:
  46. ``` javascript
  47. form.submit('http://example.org/', function(err, res) {
  48. // res – response object (http.IncomingMessage) //
  49. res.resume();
  50. });
  51. ```
  52. For more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods.
  53. ### Custom options
  54. You can provide custom options, such as `maxDataSize`:
  55. ``` javascript
  56. var FormData = require('form-data');
  57. var form = new FormData({ maxDataSize: 20971520 });
  58. form.append('my_field', 'my value');
  59. form.append('my_buffer', /* something big */);
  60. ```
  61. 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)
  62. ### Alternative submission methods
  63. You can use node's http client interface:
  64. ``` javascript
  65. var http = require('http');
  66. var request = http.request({
  67. method: 'post',
  68. host: 'example.org',
  69. path: '/upload',
  70. headers: form.getHeaders()
  71. });
  72. form.pipe(request);
  73. request.on('response', function(res) {
  74. console.log(res.statusCode);
  75. });
  76. ```
  77. Or if you would prefer the `'Content-Length'` header to be set for you:
  78. ``` javascript
  79. form.submit('example.org/upload', function(err, res) {
  80. console.log(res.statusCode);
  81. });
  82. ```
  83. To use custom headers and pre-known length in parts:
  84. ``` javascript
  85. var CRLF = '\r\n';
  86. var form = new FormData();
  87. var options = {
  88. header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF,
  89. knownLength: 1
  90. };
  91. form.append('my_buffer', buffer, options);
  92. form.submit('http://example.com/', function(err, res) {
  93. if (err) throw err;
  94. console.log('Done');
  95. });
  96. ```
  97. 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:
  98. ``` javascript
  99. someModule.stream(function(err, stdout, stderr) {
  100. if (err) throw err;
  101. var form = new FormData();
  102. form.append('file', stdout, {
  103. filename: 'unicycle.jpg', // ... or:
  104. filepath: 'photos/toys/unicycle.jpg',
  105. contentType: 'image/jpeg',
  106. knownLength: 19806
  107. });
  108. form.submit('http://example.com/', function(err, res) {
  109. if (err) throw err;
  110. console.log('Done');
  111. });
  112. });
  113. ```
  114. 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).
  115. 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:
  116. ``` javascript
  117. form.submit({
  118. host: 'example.com',
  119. path: '/probably.php?extra=params',
  120. auth: 'username:password'
  121. }, function(err, res) {
  122. console.log(res.statusCode);
  123. });
  124. ```
  125. 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()`:
  126. ``` javascript
  127. form.submit({
  128. host: 'example.com',
  129. path: '/surelynot.php',
  130. headers: {'x-test-header': 'test-header-value'}
  131. }, function(err, res) {
  132. console.log(res.statusCode);
  133. });
  134. ```
  135. ### Methods
  136. - [_Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )](https://github.com/form-data/form-data#void-append-string-field-mixed-value--mixed-options-).
  137. - [_Headers_ getHeaders( [**Headers** _userHeaders_] )](https://github.com/form-data/form-data#array-getheaders-array-userheaders-)
  138. - [_String_ getBoundary()](https://github.com/form-data/form-data#string-getboundary)
  139. - [_Void_ setBoundary()](https://github.com/form-data/form-data#void-setboundary)
  140. - [_Buffer_ getBuffer()](https://github.com/form-data/form-data#buffer-getbuffer)
  141. - [_Integer_ getLengthSync()](https://github.com/form-data/form-data#integer-getlengthsync)
  142. - [_Integer_ getLength( **function** _callback_ )](https://github.com/form-data/form-data#integer-getlength-function-callback-)
  143. - [_Boolean_ hasKnownLength()](https://github.com/form-data/form-data#boolean-hasknownlength)
  144. - [_Request_ submit( _params_, **function** _callback_ )](https://github.com/form-data/form-data#request-submit-params-function-callback-)
  145. - [_String_ toString()](https://github.com/form-data/form-data#string-tostring)
  146. #### _Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )
  147. 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.
  148. ```javascript
  149. var form = new FormData();
  150. form.append( 'my_string', 'my value' );
  151. form.append( 'my_integer', 1 );
  152. form.append( 'my_boolean', true );
  153. form.append( 'my_buffer', new Buffer(10) );
  154. form.append( 'my_array_as_json', JSON.stringify( ['bird','cute'] ) )
  155. ```
  156. You may provide a string for options, or an object.
  157. ```javascript
  158. // Set filename by providing a string for options
  159. form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' );
  160. // provide an object.
  161. form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806} );
  162. ```
  163. #### _Headers_ getHeaders( [**Headers** _userHeaders_] )
  164. This method adds the correct `content-type` header to the provided array of `userHeaders`.
  165. #### _String_ getBoundary()
  166. Return the boundary of the formData. By default, the boundary consists of 26 `-` followed by 24 numbers
  167. for example:
  168. ```javascript
  169. --------------------------515890814546601021194782
  170. ```
  171. #### _Void_ setBoundary(String _boundary_)
  172. Set the boundary string, overriding the default behavior described above.
  173. _Note: The boundary must be unique and may not appear in the data._
  174. #### _Buffer_ getBuffer()
  175. Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data.
  176. ```javascript
  177. var form = new FormData();
  178. form.append( 'my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]) );
  179. form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') );
  180. axios.post( 'https://example.com/path/to/api',
  181. form.getBuffer(),
  182. form.getHeaders()
  183. )
  184. ```
  185. **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.
  186. #### _Integer_ getLengthSync()
  187. Same as `getLength` but synchronous.
  188. _Note: getLengthSync __doesn't__ calculate streams length._
  189. #### _Integer_ getLength( **function** _callback_ )
  190. Returns the `Content-Length` async. The callback is used to handle errors and continue once the length has been calculated
  191. ```javascript
  192. this.getLength(function(err, length) {
  193. if (err) {
  194. this._error(err);
  195. return;
  196. }
  197. // add content length
  198. request.setHeader('Content-Length', length);
  199. ...
  200. }.bind(this));
  201. ```
  202. #### _Boolean_ hasKnownLength()
  203. Checks if the length of added values is known.
  204. #### _Request_ submit( _params_, **function** _callback_ )
  205. Submit the form to a web application.
  206. ```javascript
  207. var form = new FormData();
  208. form.append( 'my_string', 'Hello World' );
  209. form.submit( 'http://example.com/', function(err, res) {
  210. // res – response object (http.IncomingMessage) //
  211. res.resume();
  212. } );
  213. ```
  214. #### _String_ toString()
  215. Returns the form data as a string. Don't use this if you are sending files or buffers, use `getBuffer()` instead.
  216. ### Integration with other libraries
  217. #### Request
  218. Form submission using [request](https://github.com/request/request):
  219. ```javascript
  220. var formData = {
  221. my_field: 'my_value',
  222. my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
  223. };
  224. request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
  225. if (err) {
  226. return console.error('upload failed:', err);
  227. }
  228. console.log('Upload successful! Server responded with:', body);
  229. });
  230. ```
  231. For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads).
  232. #### node-fetch
  233. You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch):
  234. ```javascript
  235. var form = new FormData();
  236. form.append('a', 1);
  237. fetch('http://example.com', { method: 'POST', body: form })
  238. .then(function(res) {
  239. return res.json();
  240. }).then(function(json) {
  241. console.log(json);
  242. });
  243. ```
  244. #### axios
  245. In Node.js you can post a file using [axios](https://github.com/axios/axios):
  246. ```javascript
  247. const form = new FormData();
  248. const stream = fs.createReadStream(PATH_TO_FILE);
  249. form.append('image', stream);
  250. // In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`
  251. const formHeaders = form.getHeaders();
  252. axios.post('http://example.com', form, {
  253. headers: {
  254. ...formHeaders,
  255. },
  256. })
  257. .then(response => response)
  258. .catch(error => error)
  259. ```
  260. ## Notes
  261. - ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround.
  262. - Starting version `2.x` FormData has dropped support for `node@0.10.x`.
  263. - Starting version `3.x` FormData has dropped support for `node@4.x`.
  264. ## License
  265. Form-Data is released under the [MIT](License) license.