README.md.bak 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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:4.x-9.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:4.x-9.x)](https://travis-ci.org/form-data/form-data)
  7. [![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/form-data/master.svg?label=windows:4.x-9.x)](https://ci.appveyor.com/project/alexindigo/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. [![bitHound Overall Score](https://www.bithound.io/github/form-data/form-data/badges/score.svg)](https://www.bithound.io/github/form-data/form-data)
  11. ## Install
  12. ```
  13. npm install --save form-data
  14. ```
  15. ## Usage
  16. In this example we are constructing a form with 3 fields that contain a string,
  17. a buffer and a file stream.
  18. ``` javascript
  19. var FormData = require('form-data');
  20. var fs = require('fs');
  21. var form = new FormData();
  22. form.append('my_field', 'my value');
  23. form.append('my_buffer', new Buffer(10));
  24. form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
  25. ```
  26. Also you can use http-response stream:
  27. ``` javascript
  28. var FormData = require('form-data');
  29. var http = require('http');
  30. var form = new FormData();
  31. http.request('http://nodejs.org/images/logo.png', function(response) {
  32. form.append('my_field', 'my value');
  33. form.append('my_buffer', new Buffer(10));
  34. form.append('my_logo', response);
  35. });
  36. ```
  37. Or @mikeal's [request](https://github.com/request/request) stream:
  38. ``` javascript
  39. var FormData = require('form-data');
  40. var request = require('request');
  41. var form = new FormData();
  42. form.append('my_field', 'my value');
  43. form.append('my_buffer', new Buffer(10));
  44. form.append('my_logo', request('http://nodejs.org/images/logo.png'));
  45. ```
  46. In order to submit this form to a web application, call ```submit(url, [callback])``` method:
  47. ``` javascript
  48. form.submit('http://example.org/', function(err, res) {
  49. // res – response object (http.IncomingMessage) //
  50. res.resume();
  51. });
  52. ```
  53. For more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods.
  54. ### Custom options
  55. You can provide custom options, such as `maxDataSize`:
  56. ``` javascript
  57. var FormData = require('form-data');
  58. var form = new FormData({ maxDataSize: 20971520 });
  59. form.append('my_field', 'my value');
  60. form.append('my_buffer', /* something big */);
  61. ```
  62. 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)
  63. ### Alternative submission methods
  64. You can use node's http client interface:
  65. ``` javascript
  66. var http = require('http');
  67. var request = http.request({
  68. method: 'post',
  69. host: 'example.org',
  70. path: '/upload',
  71. headers: form.getHeaders()
  72. });
  73. form.pipe(request);
  74. request.on('response', function(res) {
  75. console.log(res.statusCode);
  76. });
  77. ```
  78. Or if you would prefer the `'Content-Length'` header to be set for you:
  79. ``` javascript
  80. form.submit('example.org/upload', function(err, res) {
  81. console.log(res.statusCode);
  82. });
  83. ```
  84. To use custom headers and pre-known length in parts:
  85. ``` javascript
  86. var CRLF = '\r\n';
  87. var form = new FormData();
  88. var options = {
  89. header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF,
  90. knownLength: 1
  91. };
  92. form.append('my_buffer', buffer, options);
  93. form.submit('http://example.com/', function(err, res) {
  94. if (err) throw err;
  95. console.log('Done');
  96. });
  97. ```
  98. 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:
  99. ``` javascript
  100. someModule.stream(function(err, stdout, stderr) {
  101. if (err) throw err;
  102. var form = new FormData();
  103. form.append('file', stdout, {
  104. filename: 'unicycle.jpg', // ... or:
  105. filepath: 'photos/toys/unicycle.jpg',
  106. contentType: 'image/jpeg',
  107. knownLength: 19806
  108. });
  109. form.submit('http://example.com/', function(err, res) {
  110. if (err) throw err;
  111. console.log('Done');
  112. });
  113. });
  114. ```
  115. 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).
  116. 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:
  117. ``` javascript
  118. form.submit({
  119. host: 'example.com',
  120. path: '/probably.php?extra=params',
  121. auth: 'username:password'
  122. }, function(err, res) {
  123. console.log(res.statusCode);
  124. });
  125. ```
  126. 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()`:
  127. ``` javascript
  128. form.submit({
  129. host: 'example.com',
  130. path: '/surelynot.php',
  131. headers: {'x-test-header': 'test-header-value'}
  132. }, function(err, res) {
  133. console.log(res.statusCode);
  134. });
  135. ```
  136. ### Integration with other libraries
  137. #### Request
  138. Form submission using [request](https://github.com/request/request):
  139. ```javascript
  140. var formData = {
  141. my_field: 'my_value',
  142. my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
  143. };
  144. request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
  145. if (err) {
  146. return console.error('upload failed:', err);
  147. }
  148. console.log('Upload successful! Server responded with:', body);
  149. });
  150. ```
  151. For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads).
  152. #### node-fetch
  153. You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch):
  154. ```javascript
  155. var form = new FormData();
  156. form.append('a', 1);
  157. fetch('http://example.com', { method: 'POST', body: form })
  158. .then(function(res) {
  159. return res.json();
  160. }).then(function(json) {
  161. console.log(json);
  162. });
  163. ```
  164. ## Notes
  165. - ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround.
  166. - Starting version `2.x` FormData has dropped support for `node@0.10.x`.
  167. ## License
  168. Form-Data is released under the [MIT](License) license.