Skip to content

Commit

Permalink
Merge pull request #78 from abh/multipart-content-length
Browse files Browse the repository at this point in the history
Multipart content length
  • Loading branch information
danwrong committed May 2, 2012
2 parents 976692a + 88c1437 commit 254891d
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 4 deletions.
4 changes: 2 additions & 2 deletions README.md
Expand Up @@ -147,14 +147,14 @@ rest.post('http://user:pass@service.com/action', {
}
});

// multipart request sending a file and using https
// multipart request sending a 321567 byte long file using https
rest.post('https://twaud.io/api/v1/upload.json', {
multipart: true,
username: 'danwrong',
password: 'wouldntyouliketoknow',
data: {
'sound[message]': 'hello from restler!',
'sound[file]': rest.file('doug-e-fresh_the-show.mp3', null, null, null, 'audio/mpeg')
'sound[file]': rest.file('doug-e-fresh_the-show.mp3', null, 321567, null, 'audio/mpeg')
}
}).on('complete', function(data) {
sys.puts(data.audio_url);
Expand Down
2 changes: 2 additions & 0 deletions lib/multipartform.js
Expand Up @@ -87,6 +87,8 @@ Part.prototype = {
valueSize = this.value.fileSize;
} else if (this.value.data) {
valueSize = this.value.data.length;
} else if (typeof this.value === 'number') {
valueSize = this.value.toString().length;
} else {
valueSize = this.value.length;
}
Expand Down
7 changes: 7 additions & 0 deletions lib/restler.js
Expand Up @@ -55,6 +55,13 @@ function Request(uri, options) {

if (this.options.multipart) {
this.headers['Content-Type'] = 'multipart/form-data; boundary=' + multipart.defaultBoundary;
var multipart_size = multipart.sizeOf(this.options.data, multipart.defaultBoundary);
if (typeof multipart_size === 'number' && multipart_size === multipart_size) {
this.headers['Content-Length'] = multipart_size;
}
else {
console.log("Building multipart request without Content-Length header, please specify all file sizes");
}
} else {
if (typeof this.options.data == 'object') {
this.options.data = qs.stringify(this.options.data);
Expand Down
6 changes: 4 additions & 2 deletions test/restler.js
Expand Up @@ -277,12 +277,14 @@ module.exports['Multipart'] = {

'Test multipart request with simple vars': function(test) {
rest.post(host, {
data: { a: 1, b: 'thing' },
data: { a: 10, b: 'thing' },
multipart: true
}).on('complete', function(data) {
test.re(data, /content-type\: multipart\/form-data/, 'should set "content-type" header')
test.re(data, /name="a"(\s)+1/, 'should send a=1');
test.re(data, /name="a"(\s)+10/, 'should send a=10');
test.re(data, /name="b"(\s)+thing/, 'should send b=thing');
test.re(data, /content-length: 200/, 'should send content-length header');

test.done();
});
}
Expand Down

0 comments on commit 254891d

Please sign in to comment.