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.

form_data.js 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. var CombinedStream = require('combined-stream');
  2. var util = require('util');
  3. var path = require('path');
  4. var http = require('http');
  5. var https = require('https');
  6. var parseUrl = require('url').parse;
  7. var fs = require('fs');
  8. var mime = require('mime-types');
  9. var asynckit = require('asynckit');
  10. var populate = require('./populate.js');
  11. // Public API
  12. module.exports = FormData;
  13. // make it a Stream
  14. util.inherits(FormData, CombinedStream);
  15. /**
  16. * Create readable "multipart/form-data" streams.
  17. * Can be used to submit forms
  18. * and file uploads to other web applications.
  19. *
  20. * @constructor
  21. * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream
  22. */
  23. function FormData(options) {
  24. if (!(this instanceof FormData)) {
  25. return new FormData(options);
  26. }
  27. this._overheadLength = 0;
  28. this._valueLength = 0;
  29. this._valuesToMeasure = [];
  30. CombinedStream.call(this);
  31. options = options || {};
  32. for (var option in options) {
  33. this[option] = options[option];
  34. }
  35. }
  36. FormData.LINE_BREAK = '\r\n';
  37. FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream';
  38. FormData.prototype.append = function(field, value, options) {
  39. options = options || {};
  40. // allow filename as single option
  41. if (typeof options == 'string') {
  42. options = {filename: options};
  43. }
  44. var append = CombinedStream.prototype.append.bind(this);
  45. // all that streamy business can't handle numbers
  46. if (typeof value == 'number') {
  47. value = '' + value;
  48. }
  49. // https://github.com/felixge/node-form-data/issues/38
  50. if (util.isArray(value)) {
  51. // Please convert your array into string
  52. // the way web server expects it
  53. this._error(new Error('Arrays are not supported.'));
  54. return;
  55. }
  56. var header = this._multiPartHeader(field, value, options);
  57. var footer = this._multiPartFooter();
  58. append(header);
  59. append(value);
  60. append(footer);
  61. // pass along options.knownLength
  62. this._trackLength(header, value, options);
  63. };
  64. FormData.prototype._trackLength = function(header, value, options) {
  65. var valueLength = 0;
  66. // used w/ getLengthSync(), when length is known.
  67. // e.g. for streaming directly from a remote server,
  68. // w/ a known file a size, and not wanting to wait for
  69. // incoming file to finish to get its size.
  70. if (options.knownLength != null) {
  71. valueLength += +options.knownLength;
  72. } else if (Buffer.isBuffer(value)) {
  73. valueLength = value.length;
  74. } else if (typeof value === 'string') {
  75. valueLength = Buffer.byteLength(value);
  76. }
  77. this._valueLength += valueLength;
  78. // @check why add CRLF? does this account for custom/multiple CRLFs?
  79. this._overheadLength +=
  80. Buffer.byteLength(header) +
  81. FormData.LINE_BREAK.length;
  82. // empty or either doesn't have path or not an http response
  83. if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) {
  84. return;
  85. }
  86. // no need to bother with the length
  87. if (!options.knownLength) {
  88. this._valuesToMeasure.push(value);
  89. }
  90. };
  91. FormData.prototype._lengthRetriever = function(value, callback) {
  92. if (value.hasOwnProperty('fd')) {
  93. // take read range into a account
  94. // `end` = Infinity –> read file till the end
  95. //
  96. // TODO: Looks like there is bug in Node fs.createReadStream
  97. // it doesn't respect `end` options without `start` options
  98. // Fix it when node fixes it.
  99. // https://github.com/joyent/node/issues/7819
  100. if (value.end != undefined && value.end != Infinity && value.start != undefined) {
  101. // when end specified
  102. // no need to calculate range
  103. // inclusive, starts with 0
  104. callback(null, value.end + 1 - (value.start ? value.start : 0));
  105. // not that fast snoopy
  106. } else {
  107. // still need to fetch file size from fs
  108. fs.stat(value.path, function(err, stat) {
  109. var fileSize;
  110. if (err) {
  111. callback(err);
  112. return;
  113. }
  114. // update final size based on the range options
  115. fileSize = stat.size - (value.start ? value.start : 0);
  116. callback(null, fileSize);
  117. });
  118. }
  119. // or http response
  120. } else if (value.hasOwnProperty('httpVersion')) {
  121. callback(null, +value.headers['content-length']);
  122. // or request stream http://github.com/mikeal/request
  123. } else if (value.hasOwnProperty('httpModule')) {
  124. // wait till response come back
  125. value.on('response', function(response) {
  126. value.pause();
  127. callback(null, +response.headers['content-length']);
  128. });
  129. value.resume();
  130. // something else
  131. } else {
  132. callback('Unknown stream');
  133. }
  134. };
  135. FormData.prototype._multiPartHeader = function(field, value, options) {
  136. // custom header specified (as string)?
  137. // it becomes responsible for boundary
  138. // (e.g. to handle extra CRLFs on .NET servers)
  139. if (typeof options.header == 'string') {
  140. return options.header;
  141. }
  142. var contentDisposition = this._getContentDisposition(value, options);
  143. var contentType = this._getContentType(value, options);
  144. var contents = '';
  145. var headers = {
  146. // add custom disposition as third element or keep it two elements if not
  147. 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []),
  148. // if no content type. allow it to be empty array
  149. 'Content-Type': [].concat(contentType || [])
  150. };
  151. // allow custom headers.
  152. if (typeof options.header == 'object') {
  153. populate(headers, options.header);
  154. }
  155. var header;
  156. for (var prop in headers) {
  157. if (!headers.hasOwnProperty(prop)) continue;
  158. header = headers[prop];
  159. // skip nullish headers.
  160. if (header == null) {
  161. continue;
  162. }
  163. // convert all headers to arrays.
  164. if (!Array.isArray(header)) {
  165. header = [header];
  166. }
  167. // add non-empty headers.
  168. if (header.length) {
  169. contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK;
  170. }
  171. }
  172. return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK;
  173. };
  174. FormData.prototype._getContentDisposition = function(value, options) {
  175. var filename
  176. , contentDisposition
  177. ;
  178. if (typeof options.filepath === 'string') {
  179. // custom filepath for relative paths
  180. filename = path.normalize(options.filepath).replace(/\\/g, '/');
  181. } else if (options.filename || value.name || value.path) {
  182. // custom filename take precedence
  183. // formidable and the browser add a name property
  184. // fs- and request- streams have path property
  185. filename = path.basename(options.filename || value.name || value.path);
  186. } else if (value.readable && value.hasOwnProperty('httpVersion')) {
  187. // or try http response
  188. filename = path.basename(value.client._httpMessage.path || '');
  189. }
  190. if (filename) {
  191. contentDisposition = 'filename="' + filename + '"';
  192. }
  193. return contentDisposition;
  194. };
  195. FormData.prototype._getContentType = function(value, options) {
  196. // use custom content-type above all
  197. var contentType = options.contentType;
  198. // or try `name` from formidable, browser
  199. if (!contentType && value.name) {
  200. contentType = mime.lookup(value.name);
  201. }
  202. // or try `path` from fs-, request- streams
  203. if (!contentType && value.path) {
  204. contentType = mime.lookup(value.path);
  205. }
  206. // or if it's http-reponse
  207. if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) {
  208. contentType = value.headers['content-type'];
  209. }
  210. // or guess it from the filepath or filename
  211. if (!contentType && (options.filepath || options.filename)) {
  212. contentType = mime.lookup(options.filepath || options.filename);
  213. }
  214. // fallback to the default content type if `value` is not simple value
  215. if (!contentType && typeof value == 'object') {
  216. contentType = FormData.DEFAULT_CONTENT_TYPE;
  217. }
  218. return contentType;
  219. };
  220. FormData.prototype._multiPartFooter = function() {
  221. return function(next) {
  222. var footer = FormData.LINE_BREAK;
  223. var lastPart = (this._streams.length === 0);
  224. if (lastPart) {
  225. footer += this._lastBoundary();
  226. }
  227. next(footer);
  228. }.bind(this);
  229. };
  230. FormData.prototype._lastBoundary = function() {
  231. return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK;
  232. };
  233. FormData.prototype.getHeaders = function(userHeaders) {
  234. var header;
  235. var formHeaders = {
  236. 'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
  237. };
  238. for (header in userHeaders) {
  239. if (userHeaders.hasOwnProperty(header)) {
  240. formHeaders[header.toLowerCase()] = userHeaders[header];
  241. }
  242. }
  243. return formHeaders;
  244. };
  245. FormData.prototype.getBoundary = function() {
  246. if (!this._boundary) {
  247. this._generateBoundary();
  248. }
  249. return this._boundary;
  250. };
  251. FormData.prototype.getBuffer = function() {
  252. var dataBuffer = new Buffer.alloc( 0 );
  253. var boundary = this.getBoundary();
  254. // Create the form content. Add Line breaks to the end of data.
  255. for (var i = 0, len = this._streams.length; i < len; i++) {
  256. if (typeof this._streams[i] !== 'function') {
  257. // Add content to the buffer.
  258. if(Buffer.isBuffer(this._streams[i])) {
  259. dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]);
  260. }else {
  261. dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]);
  262. }
  263. // Add break after content.
  264. if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) {
  265. dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] );
  266. }
  267. }
  268. }
  269. // Add the footer and return the Buffer object.
  270. return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] );
  271. };
  272. FormData.prototype._generateBoundary = function() {
  273. // This generates a 50 character boundary similar to those used by Firefox.
  274. // They are optimized for boyer-moore parsing.
  275. var boundary = '--------------------------';
  276. for (var i = 0; i < 24; i++) {
  277. boundary += Math.floor(Math.random() * 10).toString(16);
  278. }
  279. this._boundary = boundary;
  280. };
  281. // Note: getLengthSync DOESN'T calculate streams length
  282. // As workaround one can calculate file size manually
  283. // and add it as knownLength option
  284. FormData.prototype.getLengthSync = function() {
  285. var knownLength = this._overheadLength + this._valueLength;
  286. // Don't get confused, there are 3 "internal" streams for each keyval pair
  287. // so it basically checks if there is any value added to the form
  288. if (this._streams.length) {
  289. knownLength += this._lastBoundary().length;
  290. }
  291. // https://github.com/form-data/form-data/issues/40
  292. if (!this.hasKnownLength()) {
  293. // Some async length retrievers are present
  294. // therefore synchronous length calculation is false.
  295. // Please use getLength(callback) to get proper length
  296. this._error(new Error('Cannot calculate proper length in synchronous way.'));
  297. }
  298. return knownLength;
  299. };
  300. // Public API to check if length of added values is known
  301. // https://github.com/form-data/form-data/issues/196
  302. // https://github.com/form-data/form-data/issues/262
  303. FormData.prototype.hasKnownLength = function() {
  304. var hasKnownLength = true;
  305. if (this._valuesToMeasure.length) {
  306. hasKnownLength = false;
  307. }
  308. return hasKnownLength;
  309. };
  310. FormData.prototype.getLength = function(cb) {
  311. var knownLength = this._overheadLength + this._valueLength;
  312. if (this._streams.length) {
  313. knownLength += this._lastBoundary().length;
  314. }
  315. if (!this._valuesToMeasure.length) {
  316. process.nextTick(cb.bind(this, null, knownLength));
  317. return;
  318. }
  319. asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
  320. if (err) {
  321. cb(err);
  322. return;
  323. }
  324. values.forEach(function(length) {
  325. knownLength += length;
  326. });
  327. cb(null, knownLength);
  328. });
  329. };
  330. FormData.prototype.submit = function(params, cb) {
  331. var request
  332. , options
  333. , defaults = {method: 'post'}
  334. ;
  335. // parse provided url if it's string
  336. // or treat it as options object
  337. if (typeof params == 'string') {
  338. params = parseUrl(params);
  339. options = populate({
  340. port: params.port,
  341. path: params.pathname,
  342. host: params.hostname,
  343. protocol: params.protocol
  344. }, defaults);
  345. // use custom params
  346. } else {
  347. options = populate(params, defaults);
  348. // if no port provided use default one
  349. if (!options.port) {
  350. options.port = options.protocol == 'https:' ? 443 : 80;
  351. }
  352. }
  353. // put that good code in getHeaders to some use
  354. options.headers = this.getHeaders(params.headers);
  355. // https if specified, fallback to http in any other case
  356. if (options.protocol == 'https:') {
  357. request = https.request(options);
  358. } else {
  359. request = http.request(options);
  360. }
  361. // get content length and fire away
  362. this.getLength(function(err, length) {
  363. if (err) {
  364. this._error(err);
  365. return;
  366. }
  367. // add content length
  368. request.setHeader('Content-Length', length);
  369. this.pipe(request);
  370. if (cb) {
  371. var onResponse;
  372. var callback = function (error, responce) {
  373. request.removeListener('error', callback);
  374. request.removeListener('response', onResponse);
  375. return cb.call(this, error, responce);
  376. };
  377. onResponse = callback.bind(this, null);
  378. request.on('error', callback);
  379. request.on('response', onResponse);
  380. }
  381. }.bind(this));
  382. return request;
  383. };
  384. FormData.prototype._error = function(err) {
  385. if (!this.error) {
  386. this.error = err;
  387. this.pause();
  388. this.emit('error', err);
  389. }
  390. };
  391. FormData.prototype.toString = function () {
  392. return '[object FormData]';
  393. };