Search code examples
javascriptajaxnw.js

Multipart/form-data request by nw.js


I need to send POST data to server from nw.js. Data conents simple name-value pairs and one file, ie, request type will be multipart/form-data. All data should be sent per one request.

I use a XMLHttpRequest and FormData to send my data. Code:

function toArrayBuffer(buffer) {        // convert Node's Buffer to ArrayBuffer
    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' );     // some plain data;
var fs = require('fs');
var buff;

fs.readFile( data.path, function ( err, data ) {    // data.path contents full path to the file
    if( err ) {
        console.log( 'file reading error' );
        //  handling a errors
    }else{
        console.log('reading complete');
        buff = data;                        // buffer contains data, checked
        send( );
    };
});

function send() {
    var blob = new global.window.Blob( [toArrayBuffer(buff)], { type:'image/jpeg' } );  // here is a problem, I think
    fData.append( 'file', blob );
    // I've tried some cases:
    // var blob = new Blob( toArrayBuffer(buff), { type:'image/jpeg' } );  //without array braces it throws a error: The 1st argument provided is either null, or an invalid Array object.
    // var blob = new Blob( buff, { type:'image/jpeg' } );  //  directly, same error

    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 );
}

XMLHttpRequest send all data except the file. Here is request payload:

------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--

File section is empty.

I also have tried to pass Buffer directly to FormData. In this case file sends but server doesn't recognize file as a file - it puts file in a string instead (common PHP server).

Thanks


Solution

  • I solve it with form-data library:

    var FormData = require('form-data');
    var form = new FormData();
    var fs = require('fs');
    form.append( 'email', email );
    form.append( 'foo', 'bar' );
    form.append('logo', fs.createReadStream(fileOnDisk)); // attach file
    form.submit(url, function(err, res) { ... }