I'm trying to build HTTP multipart form data in JavaScript (on the server for Meteor.js HTTP request).
Here is the Meteor code that sends POST request.
var res = HTTP.post(url, {
headers: formatted.headers,
content: formatted.content
});
I'm preparing headers and content using this code.
function MultipartFormData(parts) {
var boundary = (new Date()).getTime();
var bodyParts = [];
_.each(parts, function (value, key) {
value.data = (new Buffer(value.data)).toString('binary');
bodyParts.push(
'---------------------------' + boundary,
'Content-Disposition: form-data; name="' + key + '"; filename="' + value.filename + '"',
'Content-Type: ' + value.contentType,
'',
value.data);
});
bodyParts.push('---------------------------' + boundary + '--', '');
var bodyString = bodyParts.join('\r\n');
return {
content: bodyString,
headers: {
'Content-Type': 'multipart/form-data; boundary=' + '---------------------------' + boundary,
'Content-Length': bodyString.length
}
}
}
Details about file:
key = 'file'
value.filename = 'file.png'
value.contentType = 'image/png'
value.data is an Uint8Array
Server is unable to process this request. When I'm using standard Node.js request object and FormBuilder using the same data everything work properly. I'm just requesting http connection between two servers. Could anyone tell me what is wrong with my code? I'm not the expert in HTTP protocol and I have only shreds of information about generating HTTP request's content.
And one more thing. I've tried converting Uint8Array to Buffer, ArrayBuffer, String and it also didn't work.
EDIT:
I've made test what is the http body when sending the same file in Firefox and in my app:
Firefox:
Content-Type: multipart/form-data; boundary=---------------------------19039834425958857471335503868
Content-Length: 299
-----------------------------19039834425958857471335503868
Content-Disposition: form-data; name="file"; filename="test.png"
Content-Type: image/png
PNG
IHDR
·ü]þPLTEÿâ 7
IDAT×cÀÚqÅIEND®B`
-----------------------------19039834425958857471335503868--
My App:
Content-Type: multipart/form-data; boundary=---------------------------1408816255735
Content-Length: 263
---------------------------1408816255735
Content-Disposition: form-data; name="file"; filename="test.png"
Content-Type: image/png
PNG
IHDR
·ü]þPLTEÿâ 7
IDA×cÀ
ÚqÅIEND®B`
---------------------------1408816255735--
It differs a little bit but I don't know what is the source of this difference.
EDIT 2
And the server response is: Error: failed [400] Invalid multipart request with 0 mime parts.
EDIT 3
When generating body like this:
Content-Type: multipart/form-data; boundary=1408827490794
Content-Length: 213
--1408827490794
Content-Disposition: form-data; name="file"; filename="test.png"
Content-Type: image/png
PNG
IHDR
·ü]þPLTEÿâ 7
IDA×cÀ
ÚqÅIEND®B`
--1408827490794--
I get the error: Error: failed [400] Missing end boundary in multipart body.