Multipart/form-data nw.js 请求

Multipart/form-data request by nw.js

我需要从 nw.js 向服务器发送 POST 数据。数据包含简单的名称-值对和一个文件,即请求类型将为multipart/form-data。所有数据应按一个请求发送。

我使用 XMLHttpRequest 和 FormData 发送我的数据。代码:

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 发送除文件外的所有数据。这是请求负载:

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

文件部分为空。

我也尝试过将 Buffer 直接传递给 FormData。 在这种情况下,文件发送,但服务器不将文件识别为文件 - 而是将文件放入字符串中(常见 PHP 服务器)。

谢谢

我用form-data库解决了:

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) { ... }