You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md.bak 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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/master.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/master.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/master.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/master.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. - [_Buffer_ getBuffer()](https://github.com/form-data/form-data#buffer-getbuffer)
  140. - [_Integer_ getLengthSync()](https://github.com/form-data/form-data#integer-getlengthsync)
  141. - [_Integer_ getLength( **function** _callback_ )](https://github.com/form-data/form-data#integer-getlength-function-callback-)
  142. - [_Boolean_ hasKnownLength()](https://github.com/form-data/form-data#boolean-hasknownlength)
  143. - [_Request_ submit( _params_, **function** _callback_ )](https://github.com/form-data/form-data#request-submit-params-function-callback-)
  144. - [_String_ toString()](https://github.com/form-data/form-data#string-tostring)
  145. #### _Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )
  146. 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.
  147. ```javascript
  148. var form = new FormData();
  149. form.append( 'my_string', 'my value' );
  150. form.append( 'my_integer', 1 );
  151. form.append( 'my_boolean', true );
  152. form.append( 'my_buffer', new Buffer(10) );
  153. form.append( 'my_array_as_json', JSON.stringify( ['bird','cute'] ) )
  154. ```
  155. You may provide a string for options, or an object.
  156. ```javascript
  157. // Set filename by providing a string for options
  158. form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' );
  159. // provide an object.
  160. form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806} );
  161. ```
  162. #### _Headers_ getHeaders( [**Headers** _userHeaders_] )
  163. This method ads the correct `content-type` header to the provided array of `userHeaders`.
  164. #### _String_ getBoundary()
  165. Return the boundary of the formData. A boundary consists of 26 `-` followed by 24 numbers
  166. for example:
  167. ```javascript
  168. --------------------------515890814546601021194782
  169. ```
  170. _Note: The boundary must be unique and may not appear in the data._
  171. #### _Buffer_ getBuffer()
  172. Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data.
  173. ```javascript
  174. var form = new FormData();
  175. form.append( 'my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]) );
  176. form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') );
  177. axios.post( 'https://example.com/path/to/api',
  178. form.getBuffer(),
  179. form.getHeaders()
  180. )
  181. ```
  182. **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.
  183. #### _Integer_ getLengthSync()
  184. Same as `getLength` but synchronous.
  185. _Note: getLengthSync __doesn't__ calculate streams length._
  186. #### _Integer_ getLength( **function** _callback_ )
  187. Returns the `Content-Length` async. The callback is used to handle errors and continue once the length has been calculated
  188. ```javascript
  189. this.getLength(function(err, length) {
  190. if (err) {
  191. this._error(err);
  192. return;
  193. }
  194. // add content length
  195. request.setHeader('Content-Length', length);
  196. ...
  197. }.bind(this));
  198. ```
  199. #### _Boolean_ hasKnownLength()
  200. Checks if the length of added values is known.
  201. #### _Request_ submit( _params_, **function** _callback_ )
  202. Submit the form to a web application.
  203. ```javascript
  204. var form = new FormData();
  205. form.append( 'my_string', 'Hello World' );
  206. form.submit( 'http://example.com/', function(err, res) {
  207. // res – response object (http.IncomingMessage) //
  208. res.resume();
  209. } );
  210. ```
  211. #### _String_ toString()
  212. Returns the form data as a string. Don't use this if you are sending files or buffers, use `getBuffer()` instead.
  213. ### Integration with other libraries
  214. #### Request
  215. Form submission using [request](https://github.com/request/request):
  216. ```javascript
  217. var formData = {
  218. my_field: 'my_value',
  219. my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
  220. };
  221. request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
  222. if (err) {
  223. return console.error('upload failed:', err);
  224. }
  225. console.log('Upload successful! Server responded with:', body);
  226. });
  227. ```
  228. For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads).
  229. #### node-fetch
  230. You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch):
  231. ```javascript
  232. var form = new FormData();
  233. form.append('a', 1);
  234. fetch('http://example.com', { method: 'POST', body: form })
  235. .then(function(res) {
  236. return res.json();
  237. }).then(function(json) {
  238. console.log(json);
  239. });
  240. ```
  241. #### axios
  242. In Node.js you can post a file using [axios](https://github.com/axios/axios):
  243. ```javascript
  244. const form = new FormData();
  245. const stream = fs.createReadStream(PATH_TO_FILE);
  246. form.append('image', stream);
  247. // In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`
  248. const formHeaders = form.getHeaders();
  249. axios.post('http://example.com', form, {
  250. headers: {
  251. ...formHeaders,
  252. },
  253. })
  254. .then(response => response)
  255. .catch(error => error)
  256. ```
  257. ## Notes
  258. - ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround.
  259. - Starting version `2.x` FormData has dropped support for `node@0.10.x`.
  260. - Starting version `3.x` FormData has dropped support for `node@4.x`.
  261. ## License
  262. Form-Data is released under the [MIT](License) license.