fcs
2025-04-10 0163870d662dc5b7d69ceff977490ede594f7d82
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/**
 * Data format:
 *
 
--FormStreamBoundary1349886663601\r\n
Content-Disposition: form-data; name="foo"\r\n
\r\n
<FIELD-CONTENT>\r\n
--FormStreamBoundary1349886663601\r\n
Content-Disposition: form-data; name="file"; filename="formstream.test.js"\r\n
Content-Type: application/javascript\r\n
\r\n
<FILE-CONTENT>\r\n
--FormStreamBoundary1349886663601\r\n
Content-Disposition: form-data; name="pic"; filename="fawave.png"\r\n
Content-Type: image/png\r\n
\r\n
<IMAGE-CONTENT>\r\n
--FormStreamBoundary1349886663601--
 
 *
 */
 
'use strict';
 
var Stream = require('stream');
var parseStream = require('pause-stream');
var util = require('util');
var mime = require('mime');
var path = require('path');
var fs = require('fs');
var destroy = require('destroy');
 
var PADDING = '--';
var NEW_LINE = '\r\n';
var NEW_LINE_BUFFER = new Buffer(NEW_LINE);
 
function FormStream() {
  if (!(this instanceof FormStream)) {
    return new FormStream();
  }
 
  FormStream.super_.call(this);
 
  this._boundary = this._generateBoundary();
  this._streams = [];
  this._buffers = [];
  this._endData = new Buffer(PADDING + this._boundary + PADDING + NEW_LINE);
  this._contentLength = 0;
  this._isAllStreamSizeKnown = true;
  this._knownStreamSize = 0;
}
 
util.inherits(FormStream, Stream);
module.exports = FormStream;
 
FormStream.prototype._generateBoundary = function() {
  // https://github.com/felixge/node-form-data/blob/master/lib/form_data.js#L162
  // This generates a 50 character boundary similar to those used by Firefox.
  // They are optimized for boyer-moore parsing.
  var boundary = '--------------------------';
  for (var i = 0; i < 24; i++) {
    boundary += Math.floor(Math.random() * 10).toString(16);
  }
 
  return boundary;
};
 
FormStream.prototype.setTotalStreamSize = function (size) {
  // this method should not make any sense if the length of each stream is known.
  if (this._isAllStreamSizeKnown) {
    return this;
  }
 
  size = size || 0;
 
  for (var i = 0; i < this._streams.length; i++) {
    size += this._streams[i][0].length;
    size += NEW_LINE_BUFFER.length; // stream field end pedding size
  }
 
  this._knownStreamSize = size;
  this._isAllStreamSizeKnown = true;
 
  return this;
};
 
FormStream.prototype.headers = function (options) {
  var headers = {
    'Content-Type': 'multipart/form-data; boundary=' + this._boundary
  };
 
  // calculate total stream size
  this._contentLength += this._knownStreamSize;
 
  // calculate length of end padding
  this._contentLength += this._endData.length;
 
  if (this._isAllStreamSizeKnown) {
    headers['Content-Length'] = String(this._contentLength);
  }
 
  if (options) {
    for (var k in options) {
      headers[k] = options[k];
    }
  }
 
  return headers;
};
 
FormStream.prototype.file = function (name, filepath, filename, filesize) {
  var mimeType = mime.lookup(filepath);
 
  if (typeof filename === 'number' && !filesize) {
    filesize = filename;
    filename = path.basename(filepath);
  } else if (!filename) {
    filename = path.basename(filepath);
  }
 
  var stream = fs.createReadStream(filepath);
 
  return this.stream(name, stream, filename, mimeType, filesize);
};
 
/**
 * Add a form field
 * @param  {String} name field name
 * @param  {String|Buffer} value field value
 * @return {this}
 */
FormStream.prototype.field = function (name, value) {
  if (!Buffer.isBuffer(value)) {
    // field(String, Number)
    // https://github.com/qiniu/nodejs-sdk/issues/123
    if (typeof value === 'number') {
      value = String(value);
    }
    value = new Buffer(value);
  }
  return this.buffer(name, value);
};
 
FormStream.prototype.stream = function (name, stream, filename, mimeType, size) {
  if (typeof mimeType === 'number' && !size) {
    size = mimeType;
    mimeType = mime.lookup(filename);
  } else if (!mimeType) {
    mimeType = mime.lookup(filename);
  }
 
  stream.once('error', this.emit.bind(this, 'error'));
  // if form stream destroy, also destroy the source stream
  this.once('destroy', function () {
    destroy(stream);
  });
 
  var leading = this._leading({ name: name, filename: filename }, mimeType);
 
  var ps = parseStream().pause();
  stream.pipe(ps);
 
  this._streams.push([leading, ps]);
 
  // if the size of this stream is known, plus the total content-length;
  // otherwise, content-length is unknown.
  if (typeof size === 'number') {
    this._knownStreamSize += leading.length;
    this._knownStreamSize += size;
    this._knownStreamSize += NEW_LINE_BUFFER.length;
  } else {
    this._isAllStreamSizeKnown = false;
  }
 
  process.nextTick(this.resume.bind(this));
 
  return this;
};
 
FormStream.prototype.buffer = function (name, buffer, filename, mimeType) {
  if (filename && !mimeType) {
    mimeType = mime.lookup(filename);
  }
 
  var disposition = { name: name };
  if (filename) {
    disposition.filename = filename;
  }
 
  var leading = this._leading(disposition, mimeType);
 
  this._buffers.push([leading, buffer]);
 
  // plus buffer length to total content-length
  this._contentLength += leading.length;
  this._contentLength += buffer.length;
  this._contentLength += NEW_LINE_BUFFER.length;
 
  process.nextTick(this.resume.bind(this));
 
  return this;
};
 
FormStream.prototype._leading = function (disposition, type) {
  var leading = [PADDING + this._boundary];
 
  var disps = [];
 
  if (disposition) {
    for (var k in disposition) {
      disps.push(k + '="' + disposition[k] + '"');
    }
  }
 
  leading.push('Content-Disposition: form-data; ' + disps.join('; '));
 
  if (type) {
    leading.push('Content-Type: ' + type);
  }
 
  leading.push('');
  leading.push('');
 
  return new Buffer(leading.join(NEW_LINE));
};
 
FormStream.prototype._emitBuffers = function () {
  if (!this._buffers.length) {
    return;
  }
 
  for (var i = 0; i < this._buffers.length; i++) {
    var item = this._buffers[i];
    this.emit('data', item[0]); // part leading
    this.emit('data', item[1]); // part content
    this.emit('data', NEW_LINE_BUFFER);
  }
 
  this._buffers = [];
};
 
FormStream.prototype._emitStream = function (item) {
  var self = this;
  // item: [ fieldData, stream ]
  self.emit('data', item[0]);
 
  var stream = item[1];
  stream.on('data', function (data) {
    self.emit('data', data);
  });
  stream.on('end', function () {
    self.emit('data', NEW_LINE_BUFFER);
    return process.nextTick(self.drain.bind(self));
  });
  stream.resume();
};
 
FormStream.prototype._emitEnd = function () {
  // ending format:
  //
  // --{boundary}--\r\n
  this.emit('data', this._endData);
  this.emit('end');
};
 
FormStream.prototype.drain = function () {
  this._emitBuffers();
 
  var item = this._streams.shift();
  if (item) {
    this._emitStream(item);
  } else {
    this._emitEnd();
  }
 
  return this;
};
 
FormStream.prototype.resume = function () {
  this.paused = false;
 
  if (!this._draining) {
    this._draining = true;
    this.drain();
  }
 
  return this;
};
 
FormStream.prototype.close = FormStream.prototype.destroy = function () {
  this.emit('destroy');
};