Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

před 5 roky
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. # Formidable
  2. [![Build Status](https://travis-ci.org/felixge/node-formidable.svg?branch=master)](https://travis-ci.org/felixge/node-formidable)
  3. ## Purpose
  4. A Node.js module for parsing form data, especially file uploads.
  5. ## Current status
  6. **Maintainers Wanted:** Please see https://github.com/felixge/node-formidable/issues/412
  7. This module was developed for [Transloadit](http://transloadit.com/), a service focused on uploading
  8. and encoding images and videos. It has been battle-tested against hundreds of GB of file uploads from
  9. a large variety of clients and is considered production-ready.
  10. ## Features
  11. * Fast (~500mb/sec), non-buffering multipart parser
  12. * Automatically writing file uploads to disk
  13. * Low memory footprint
  14. * Graceful error handling
  15. * Very high test coverage
  16. ## Installation
  17. ```sh
  18. npm i -S formidable
  19. ```
  20. This is a low-level package, and if you're using a high-level framework it may already be included. However, [Express v4](http://expressjs.com) does not include any multipart handling, nor does [body-parser](https://github.com/expressjs/body-parser).
  21. Note: Formidable requires [gently](http://github.com/felixge/node-gently) to run the unit tests, but you won't need it for just using the library.
  22. ## Example
  23. Parse an incoming file upload.
  24. ```javascript
  25. var formidable = require('formidable'),
  26. http = require('http'),
  27. util = require('util');
  28. http.createServer(function(req, res) {
  29. if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
  30. // parse a file upload
  31. var form = new formidable.IncomingForm();
  32. form.parse(req, function(err, fields, files) {
  33. res.writeHead(200, {'content-type': 'text/plain'});
  34. res.write('received upload:\n\n');
  35. res.end(util.inspect({fields: fields, files: files}));
  36. });
  37. return;
  38. }
  39. // show a file upload form
  40. res.writeHead(200, {'content-type': 'text/html'});
  41. res.end(
  42. '<form action="/upload" enctype="multipart/form-data" method="post">'+
  43. '<input type="text" name="title"><br>'+
  44. '<input type="file" name="upload" multiple="multiple"><br>'+
  45. '<input type="submit" value="Upload">'+
  46. '</form>'
  47. );
  48. }).listen(8080);
  49. ```
  50. ## API
  51. ### Formidable.IncomingForm
  52. ```javascript
  53. var form = new formidable.IncomingForm()
  54. ```
  55. Creates a new incoming form.
  56. ```javascript
  57. form.encoding = 'utf-8';
  58. ```
  59. Sets encoding for incoming form fields.
  60. ```javascript
  61. form.uploadDir = "/my/dir";
  62. ```
  63. Sets the directory for placing file uploads in. You can move them later on using
  64. `fs.rename()`. The default is `os.tmpdir()`.
  65. ```javascript
  66. form.keepExtensions = false;
  67. ```
  68. If you want the files written to `form.uploadDir` to include the extensions of the original files, set this property to `true`.
  69. ```javascript
  70. form.type
  71. ```
  72. Either 'multipart' or 'urlencoded' depending on the incoming request.
  73. ```javascript
  74. form.maxFieldsSize = 20 * 1024 * 1024;
  75. ```
  76. Limits the amount of memory all fields together (except files) can allocate in bytes.
  77. If this value is exceeded, an `'error'` event is emitted. The default
  78. size is 20MB.
  79. ```javascript
  80. form.maxFileSize = 200 * 1024 * 1024;
  81. ```
  82. Limits the size of uploaded file.
  83. If this value is exceeded, an `'error'` event is emitted. The default
  84. size is 200MB.
  85. ```javascript
  86. form.maxFields = 1000;
  87. ```
  88. Limits the number of fields that the querystring parser will decode. Defaults
  89. to 1000 (0 for unlimited).
  90. ```javascript
  91. form.hash = false;
  92. ```
  93. If you want checksums calculated for incoming files, set this to either `'sha1'` or `'md5'`.
  94. ```javascript
  95. form.multiples = false;
  96. ```
  97. If this option is enabled, when you call `form.parse`, the `files` argument will contain arrays of files for inputs which submit multiple files using the HTML5 `multiple` attribute.
  98. ```javascript
  99. form.bytesReceived
  100. ```
  101. The amount of bytes received for this form so far.
  102. ```javascript
  103. form.bytesExpected
  104. ```
  105. The expected number of bytes in this form.
  106. ```javascript
  107. form.parse(request, [cb]);
  108. ```
  109. Parses an incoming node.js `request` containing form data. If `cb` is provided, all fields and files are collected and passed to the callback:
  110. ```javascript
  111. form.parse(req, function(err, fields, files) {
  112. // ...
  113. });
  114. form.onPart(part);
  115. ```
  116. You may overwrite this method if you are interested in directly accessing the multipart stream. Doing so will disable any `'field'` / `'file'` events processing which would occur otherwise, making you fully responsible for handling the processing.
  117. ```javascript
  118. form.onPart = function(part) {
  119. part.addListener('data', function() {
  120. // ...
  121. });
  122. }
  123. ```
  124. If you want to use formidable to only handle certain parts for you, you can do so:
  125. ```javascript
  126. form.onPart = function(part) {
  127. if (!part.filename) {
  128. // let formidable handle all non-file parts
  129. form.handlePart(part);
  130. }
  131. }
  132. ```
  133. Check the code in this method for further inspiration.
  134. ### Formidable.File
  135. ```javascript
  136. file.size = 0
  137. ```
  138. The size of the uploaded file in bytes. If the file is still being uploaded (see `'fileBegin'` event), this property says how many bytes of the file have been written to disk yet.
  139. ```javascript
  140. file.path = null
  141. ```
  142. The path this file is being written to. You can modify this in the `'fileBegin'` event in
  143. case you are unhappy with the way formidable generates a temporary path for your files.
  144. ```javascript
  145. file.name = null
  146. ```
  147. The name this file had according to the uploading client.
  148. ```javascript
  149. file.type = null
  150. ```
  151. The mime type of this file, according to the uploading client.
  152. ```javascript
  153. file.lastModifiedDate = null
  154. ```
  155. A date object (or `null`) containing the time this file was last written to. Mostly
  156. here for compatibility with the [W3C File API Draft](http://dev.w3.org/2006/webapi/FileAPI/).
  157. ```javascript
  158. file.hash = null
  159. ```
  160. If hash calculation was set, you can read the hex digest out of this var.
  161. #### Formidable.File#toJSON()
  162. This method returns a JSON-representation of the file, allowing you to
  163. `JSON.stringify()` the file which is useful for logging and responding
  164. to requests.
  165. ### Events
  166. #### 'progress'
  167. Emitted after each incoming chunk of data that has been parsed. Can be used to roll your own progress bar.
  168. ```javascript
  169. form.on('progress', function(bytesReceived, bytesExpected) {
  170. });
  171. ```
  172. #### 'field'
  173. Emitted whenever a field / value pair has been received.
  174. ```javascript
  175. form.on('field', function(name, value) {
  176. });
  177. ```
  178. #### 'fileBegin'
  179. Emitted whenever a new file is detected in the upload stream. Use this event if
  180. you want to stream the file to somewhere else while buffering the upload on
  181. the file system.
  182. ```javascript
  183. form.on('fileBegin', function(name, file) {
  184. });
  185. ```
  186. #### 'file'
  187. Emitted whenever a field / file pair has been received. `file` is an instance of `File`.
  188. ```javascript
  189. form.on('file', function(name, file) {
  190. });
  191. ```
  192. #### 'error'
  193. Emitted when there is an error processing the incoming form. A request that experiences an error is automatically paused, you will have to manually call `request.resume()` if you want the request to continue firing `'data'` events.
  194. ```javascript
  195. form.on('error', function(err) {
  196. });
  197. ```
  198. #### 'aborted'
  199. Emitted when the request was aborted by the user. Right now this can be due to a 'timeout' or 'close' event on the socket. After this event is emitted, an `error` event will follow. In the future there will be a separate 'timeout' event (needs a change in the node core).
  200. ```javascript
  201. form.on('aborted', function() {
  202. });
  203. ```
  204. ##### 'end'
  205. ```javascript
  206. form.on('end', function() {
  207. });
  208. ```
  209. Emitted when the entire request has been received, and all contained files have finished flushing to disk. This is a great place for you to send your response.
  210. ## Changelog
  211. ### v1.1.1 (2017-01-15)
  212. * Fix DeprecationWarning about os.tmpDir() (Christian)
  213. * Update `buffer.write` order of arguments for Node 7 (Kornel Lesiński)
  214. * JSON Parser emits error events to the IncomingForm (alessio.montagnani)
  215. * Improved Content-Disposition parsing (Sebastien)
  216. * Access WriteStream of fs during runtime instead of include time (Jonas Amundsen)
  217. * Use built-in toString to convert buffer to hex (Charmander)
  218. * Add hash to json if present (Nick Stamas)
  219. * Add license to package.json (Simen Bekkhus)
  220. ### v1.0.14 (2013-05-03)
  221. * Add failing hash tests. (Ben Trask)
  222. * Enable hash calculation again (Eugene Girshov)
  223. * Test for immediate data events (Tim Smart)
  224. * Re-arrange IncomingForm#parse (Tim Smart)
  225. ### v1.0.13
  226. * Only update hash if update method exists (Sven Lito)
  227. * According to travis v0.10 needs to go quoted (Sven Lito)
  228. * Bumping build node versions (Sven Lito)
  229. * Additional fix for empty requests (Eugene Girshov)
  230. * Change the default to 1000, to match the new Node behaviour. (OrangeDog)
  231. * Add ability to control maxKeys in the querystring parser. (OrangeDog)
  232. * Adjust test case to work with node 0.9.x (Eugene Girshov)
  233. * Update package.json (Sven Lito)
  234. * Path adjustment according to eb4468b (Markus Ast)
  235. ### v1.0.12
  236. * Emit error on aborted connections (Eugene Girshov)
  237. * Add support for empty requests (Eugene Girshov)
  238. * Fix name/filename handling in Content-Disposition (jesperp)
  239. * Tolerate malformed closing boundary in multipart (Eugene Girshov)
  240. * Ignore preamble in multipart messages (Eugene Girshov)
  241. * Add support for application/json (Mike Frey, Carlos Rodriguez)
  242. * Add support for Base64 encoding (Elmer Bulthuis)
  243. * Add File#toJSON (TJ Holowaychuk)
  244. * Remove support for Node.js 0.4 & 0.6 (Andrew Kelley)
  245. * Documentation improvements (Sven Lito, Andre Azevedo)
  246. * Add support for application/octet-stream (Ion Lupascu, Chris Scribner)
  247. * Use os.tmpdir() to get tmp directory (Andrew Kelley)
  248. * Improve package.json (Andrew Kelley, Sven Lito)
  249. * Fix benchmark script (Andrew Kelley)
  250. * Fix scope issue in incoming_forms (Sven Lito)
  251. * Fix file handle leak on error (OrangeDog)
  252. ## License
  253. Formidable is licensed under the MIT license.
  254. ## Ports
  255. * [multipart-parser](http://github.com/FooBarWidget/multipart-parser): a C++ parser based on formidable
  256. ## Credits
  257. * [Ryan Dahl](http://twitter.com/ryah) for his work on [http-parser](http://github.com/ry/http-parser) which heavily inspired multipart_parser.js