Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
chadsmith committed Feb 7, 2012
0 parents commit 7e12fb9
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions rawformdata.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
var
fs = require('fs'),
path = require('path'),
buffer = require('buffer'),
mime = require('mime'),
crypto = require('crypto'),
CRLF = "\r\n";

var RawFormData = function() {
this.boundary = '--' + crypto.createHash('md5').update('' + +new Date).digest('hex');
this.data = [];
};

RawFormData.prototype = {
addField: function(key, value) {
this.data.push(new Buffer([
this.boundary,
'Content-Disposition: form-data; name="' + key + '";' + CRLF,
value + CRLF
].join(CRLF), 'ascii'));
},
addFile: function(name, filename, file) {
file = path.join(__dirname, filename);
this.data.push(new Buffer([
this.boundary,
'Content-Disposition: form-data; name="' + name + '"; filename="' + filename + '";',
'Content-Type: ' + (mime.lookup(file) || 'application/octet-stream') + ';' + CRLF + CRLF
].join(CRLF), 'ascii'));
this.data.push(fs.readFileSync(file));
},
getBuffer: function() {
for(var data = [], i = 0, l = this.data.length; i < l; i++)
data.push(this.data[i]);
data.push(new Buffer(this.boundary + '--', 'ascii'));
return data;
},
getHeaders: function() {
for(var data = this.getBuffer(), length = i = 0, l = data.length; i < l; i++)
length += data[i].length;
return {
'Content-Type': 'multipart/form-data; boundary="' + this.boundary.substr(2) + '"',
'Content-Length': length
};
}
};

module.exports = RawFormData;

0 comments on commit 7e12fb9

Please sign in to comment.