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.

419 lines
13 KiB

  1. # Formidable
  2. [![Build Status](https://secure.travis-ci.org/felixge/node-formidable.png?branch=master)](http://travis-ci.org/felixge/node-formidable)
  3. ## Purpose
  4. A node.js module for parsing form data, especially file uploads.
  5. ## Current status
  6. This module was developed for [Transloadit](http://transloadit.com/), a service focused on uploading
  7. and encoding images and videos. It has been battle-tested against hundreds of GB of file uploads from
  8. a large variety of clients and is considered production-ready.
  9. ## Features
  10. * Fast (~500mb/sec), non-buffering multipart parser
  11. * Automatically writing file uploads to disk
  12. * Low memory footprint
  13. * Graceful error handling
  14. * Very high test coverage
  15. ## Installation
  16. Via [npm](http://github.com/isaacs/npm):
  17. ```
  18. npm install formidable@latest
  19. ```
  20. Manually:
  21. ```
  22. git clone git://github.com/felixge/node-formidable.git formidable
  23. vim my.js
  24. # var formidable = require('./formidable');
  25. ```
  26. 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.
  27. ## Example
  28. Parse an incoming file upload.
  29. ```javascript
  30. var formidable = require('formidable'),
  31. http = require('http'),
  32. util = require('util');
  33. http.createServer(function(req, res) {
  34. if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
  35. // parse a file upload
  36. var form = new formidable.IncomingForm();
  37. form.parse(req, function(err, fields, files) {
  38. res.writeHead(200, {'content-type': 'text/plain'});
  39. res.write('received upload:\n\n');
  40. res.end(util.inspect({fields: fields, files: files}));
  41. });
  42. return;
  43. }
  44. // show a file upload form
  45. res.writeHead(200, {'content-type': 'text/html'});
  46. res.end(
  47. '<form action="/upload" enctype="multipart/form-data" method="post">'+
  48. '<input type="text" name="title"><br>'+
  49. '<input type="file" name="upload" multiple="multiple"><br>'+
  50. '<input type="submit" value="Upload">'+
  51. '</form>'
  52. );
  53. }).listen(8080);
  54. ```
  55. ## API
  56. ### Formidable.IncomingForm
  57. ```javascript
  58. var form = new formidable.IncomingForm()
  59. ```
  60. Creates a new incoming form.
  61. ```javascript
  62. form.encoding = 'utf-8';
  63. ```
  64. Sets encoding for incoming form fields.
  65. ```javascript
  66. form.uploadDir = process.env.TMP || process.env.TMPDIR || process.env.TEMP || '/tmp' || process.cwd();
  67. ```
  68. The directory for placing file uploads in. You can move them later on using
  69. `fs.rename()`. The default directory is picked at module load time depending on
  70. the first existing directory from those listed above.
  71. ```javascript
  72. form.keepExtensions = false;
  73. ```
  74. If you want the files written to `form.uploadDir` to include the extensions of the original files, set this property to `true`.
  75. ```javascript
  76. form.type
  77. ```
  78. Either 'multipart' or 'urlencoded' depending on the incoming request.
  79. ```javascript
  80. form.maxFieldsSize = 2 * 1024 * 1024;
  81. ```
  82. Limits the amount of memory a field (not file) can allocate in bytes.
  83. If this value is exceeded, an `'error'` event is emitted. The default
  84. size is 2MB.
  85. ```javascript
  86. form.maxFields = 0;
  87. ```
  88. Limits the number of fields that the querystring parser will decode. Defaults
  89. to 0 (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.bytesReceived
  96. ```
  97. The amount of bytes received for this form so far.
  98. ```javascript
  99. form.bytesExpected
  100. ```
  101. The expected number of bytes in this form.
  102. ```javascript
  103. form.parse(request, [cb]);
  104. ```
  105. Parses an incoming node.js `request` containing form data. If `cb` is provided, all fields an files are collected and passed to the callback:
  106. ```javascript
  107. form.parse(req, function(err, fields, files) {
  108. // ...
  109. });
  110. form.onPart(part);
  111. ```
  112. 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.
  113. ```javascript
  114. form.onPart = function(part) {
  115. part.addListener('data', function() {
  116. // ...
  117. });
  118. }
  119. ```
  120. If you want to use formidable to only handle certain parts for you, you can do so:
  121. ```javascript
  122. form.onPart = function(part) {
  123. if (!part.filename) {
  124. // let formidable handle all non-file parts
  125. form.handlePart(part);
  126. }
  127. }
  128. ```
  129. Check the code in this method for further inspiration.
  130. ### Formidable.File
  131. ```javascript
  132. file.size = 0
  133. ```
  134. 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.
  135. ```javascript
  136. file.path = null
  137. ```
  138. The path this file is being written to. You can modify this in the `'fileBegin'` event in
  139. case you are unhappy with the way formidable generates a temporary path for your files.
  140. ```javascript
  141. file.name = null
  142. ```
  143. The name this file had according to the uploading client.
  144. ```javascript
  145. file.type = null
  146. ```
  147. The mime type of this file, according to the uploading client.
  148. ```javascript
  149. file.lastModifiedDate = null
  150. ```
  151. A date object (or `null`) containing the time this file was last written to. Mostly
  152. here for compatibility with the [W3C File API Draft](http://dev.w3.org/2006/webapi/FileAPI/).
  153. ```javascript
  154. file.hash = null
  155. ```
  156. If hash calculation was set, you can read the hex digest out of this var.
  157. #### Formidable.File#toJSON()
  158. This method returns a JSON-representation of the file, allowing you to
  159. `JSON.stringify()` the file which is useful for logging and responding
  160. to requests.
  161. ### Events
  162. #### 'progress'
  163. ```javascript
  164. form.on('progress', function(bytesReceived, bytesExpected) {
  165. });
  166. ```
  167. Emitted after each incoming chunk of data that has been parsed. Can be used to roll your own progress bar.
  168. #### 'field'
  169. ```javascript
  170. form.on('field', function(name, value) {
  171. });
  172. ```
  173. #### 'fileBegin'
  174. Emitted whenever a field / value pair has been received.
  175. ```javascript
  176. form.on('fileBegin', function(name, file) {
  177. });
  178. ```
  179. #### 'file'
  180. Emitted whenever a new file is detected in the upload stream. Use this even if
  181. you want to stream the file to somewhere else while buffering the upload on
  182. the file system.
  183. Emitted whenever a field / file pair has been received. `file` is an instance of `File`.
  184. ```javascript
  185. form.on('file', function(name, file) {
  186. });
  187. ```
  188. #### 'error'
  189. 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.
  190. ```javascript
  191. form.on('error', function(err) {
  192. });
  193. ```
  194. #### 'aborted'
  195. Emitted when the request was aborted by the user. Right now this can be due to a 'timeout' or 'close' event on the socket. In the future there will be a separate 'timeout' event (needs a change in the node core).
  196. ```javascript
  197. form.on('aborted', function() {
  198. });
  199. ```
  200. ##### 'end'
  201. ```javascript
  202. form.on('end', function() {
  203. });
  204. ```
  205. 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.
  206. ## Changelog
  207. ### v1.0.14
  208. * Add failing hash tests. (Ben Trask)
  209. * Enable hash calculation again (Eugene Girshov)
  210. * Test for immediate data events (Tim Smart)
  211. * Re-arrange IncomingForm#parse (Tim Smart)
  212. ### v1.0.13
  213. * Only update hash if update method exists (Sven Lito)
  214. * According to travis v0.10 needs to go quoted (Sven Lito)
  215. * Bumping build node versions (Sven Lito)
  216. * Additional fix for empty requests (Eugene Girshov)
  217. * Change the default to 1000, to match the new Node behaviour. (OrangeDog)
  218. * Add ability to control maxKeys in the querystring parser. (OrangeDog)
  219. * Adjust test case to work with node 0.9.x (Eugene Girshov)
  220. * Update package.json (Sven Lito)
  221. * Path adjustment according to eb4468b (Markus Ast)
  222. ### v1.0.12
  223. * Emit error on aborted connections (Eugene Girshov)
  224. * Add support for empty requests (Eugene Girshov)
  225. * Fix name/filename handling in Content-Disposition (jesperp)
  226. * Tolerate malformed closing boundary in multipart (Eugene Girshov)
  227. * Ignore preamble in multipart messages (Eugene Girshov)
  228. * Add support for application/json (Mike Frey, Carlos Rodriguez)
  229. * Add support for Base64 encoding (Elmer Bulthuis)
  230. * Add File#toJSON (TJ Holowaychuk)
  231. * Remove support for Node.js 0.4 & 0.6 (Andrew Kelley)
  232. * Documentation improvements (Sven Lito, Andre Azevedo)
  233. * Add support for application/octet-stream (Ion Lupascu, Chris Scribner)
  234. * Use os.tmpDir() to get tmp directory (Andrew Kelley)
  235. * Improve package.json (Andrew Kelley, Sven Lito)
  236. * Fix benchmark script (Andrew Kelley)
  237. * Fix scope issue in incoming_forms (Sven Lito)
  238. * Fix file handle leak on error (OrangeDog)
  239. ### v1.0.11
  240. * Calculate checksums for incoming files (sreuter)
  241. * Add definition parameters to "IncomingForm" as an argument (Math-)
  242. ### v1.0.10
  243. * Make parts to be proper Streams (Matt Robenolt)
  244. ### v1.0.9
  245. * Emit progress when content length header parsed (Tim Koschützki)
  246. * Fix Readme syntax due to GitHub changes (goob)
  247. * Replace references to old 'sys' module in Readme with 'util' (Peter Sugihara)
  248. ### v1.0.8
  249. * Strip potentially unsafe characters when using `keepExtensions: true`.
  250. * Switch to utest / urun for testing
  251. * Add travis build
  252. ### v1.0.7
  253. * Remove file from package that was causing problems when installing on windows. (#102)
  254. * Fix typos in Readme (Jason Davies).
  255. ### v1.0.6
  256. * Do not default to the default to the field name for file uploads where
  257. filename="".
  258. ### v1.0.5
  259. * Support filename="" in multipart parts
  260. * Explain unexpected end() errors in parser better
  261. **Note:** Starting with this version, formidable emits 'file' events for empty
  262. file input fields. Previously those were incorrectly emitted as regular file
  263. input fields with value = "".
  264. ### v1.0.4
  265. * Detect a good default tmp directory regardless of platform. (#88)
  266. ### v1.0.3
  267. * Fix problems with utf8 characters (#84) / semicolons in filenames (#58)
  268. * Small performance improvements
  269. * New test suite and fixture system
  270. ### v1.0.2
  271. * Exclude node\_modules folder from git
  272. * Implement new `'aborted'` event
  273. * Fix files in example folder to work with recent node versions
  274. * Make gently a devDependency
  275. [See Commits](https://github.com/felixge/node-formidable/compare/v1.0.1...v1.0.2)
  276. ### v1.0.1
  277. * Fix package.json to refer to proper main directory. (#68, Dean Landolt)
  278. [See Commits](https://github.com/felixge/node-formidable/compare/v1.0.0...v1.0.1)
  279. ### v1.0.0
  280. * Add support for multipart boundaries that are quoted strings. (Jeff Craig)
  281. This marks the beginning of development on version 2.0 which will include
  282. several architectural improvements.
  283. [See Commits](https://github.com/felixge/node-formidable/compare/v0.9.11...v1.0.0)
  284. ### v0.9.11
  285. * Emit `'progress'` event when receiving data, regardless of parsing it. (Tim Koschützki)
  286. * Use [W3C FileAPI Draft](http://dev.w3.org/2006/webapi/FileAPI/) properties for File class
  287. **Important:** The old property names of the File class will be removed in a
  288. future release.
  289. [See Commits](https://github.com/felixge/node-formidable/compare/v0.9.10...v0.9.11)
  290. ### Older releases
  291. These releases were done before starting to maintain the above Changelog:
  292. * [v0.9.10](https://github.com/felixge/node-formidable/compare/v0.9.9...v0.9.10)
  293. * [v0.9.9](https://github.com/felixge/node-formidable/compare/v0.9.8...v0.9.9)
  294. * [v0.9.8](https://github.com/felixge/node-formidable/compare/v0.9.7...v0.9.8)
  295. * [v0.9.7](https://github.com/felixge/node-formidable/compare/v0.9.6...v0.9.7)
  296. * [v0.9.6](https://github.com/felixge/node-formidable/compare/v0.9.5...v0.9.6)
  297. * [v0.9.5](https://github.com/felixge/node-formidable/compare/v0.9.4...v0.9.5)
  298. * [v0.9.4](https://github.com/felixge/node-formidable/compare/v0.9.3...v0.9.4)
  299. * [v0.9.3](https://github.com/felixge/node-formidable/compare/v0.9.2...v0.9.3)
  300. * [v0.9.2](https://github.com/felixge/node-formidable/compare/v0.9.1...v0.9.2)
  301. * [v0.9.1](https://github.com/felixge/node-formidable/compare/v0.9.0...v0.9.1)
  302. * [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)
  303. * [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)
  304. * [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)
  305. * [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)
  306. * [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)
  307. * [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)
  308. * [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)
  309. * [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0)
  310. * [v0.1.0](https://github.com/felixge/node-formidable/commits/v0.1.0)
  311. ## License
  312. Formidable is licensed under the MIT license.
  313. ## Ports
  314. * [multipart-parser](http://github.com/FooBarWidget/multipart-parser): a C++ parser based on formidable
  315. ## Credits
  316. * [Ryan Dahl](http://twitter.com/ryah) for his work on [http-parser](http://github.com/ry/http-parser) which heavily inspired multipart_parser.js