I am looking to send POST data to a server from nw.js. The data consists of simple name-value pairs and one file, meaning that the request type will be multipart/form-data
. All the data needs to be sent in one single request.
To do this, I have been using XMLHttpRequest and FormData to send my data. Here is the code snippet:
function toArrayBuffer(buffer) {
var ab = new ArrayBuffer(buffer.length);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return ab;
}
var fData = new global.window.FormData();
fData.append('email', email);
fData.append('foo', 'bar');
var fs = require('fs');
var buff;
fs.readFile(data.path, function(err, data) {
if (err) {
console.log('file reading error');
// handling errors
} else {
console.log('reading complete');
buff = data;
send();
};
});
function send() {
var blob = new global.window.Blob([toArrayBuffer(buff)], {type: 'image/jpeg'});
fData.append('file', blob);
var xhr = new global.window.XMLHttpRequest();
xhr.open("POST", url);
xhr.timeout = 30000;
xhr.onload = xhr.onerror = function() {
// handling result or errors...
};
xhr.send(fData);
}
However, I noticed that the XMLHttpRequest sends all data except for the file. The request payload is shown below:
------WebKitFormBoundaryc0ClIBTxPlqPmilD
Content-Disposition: form-data; name="email"
email
------WebKitFormBoundaryc0ClIBTxPlqPmilD
Content-Disposition: form-data; name="message_id"
4b38ad18-0501-9c0d-9cf6-e0a2fcca1898
------WebKitFormBoundaryc0ClIBTxPlqPmilD
Content-Disposition: form-data; name="foo"
bar
------WebKitFormBoundaryc0ClIBTxPlqPmilD
Content-Disposition: form-data; name="file"; filename="blob"
Content-Type: image/jpeg
------WebKitFormBoundaryc0ClIBTxPlqPmilD--
The file section appears to be empty in the request payload.
I also tried passing the Buffer directly to FormData. In this scenario, the file does get sent but the server interprets it as a string instead of a file (common issue with PHP servers).
Thank you.