2016-06-15 81 views
0

我需要從nw.js發送POST數據到服務器。數據限定了簡單的名稱 - 值對和一個文件,即請求類型將是multipart/form-data。所有數據都應該按照一個請求發送。nw.js的多部分/表單數據請求

我使用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服務器)。

感謝

+0

嗨德米特里,你解決了嗎? – bedna

+0

@bedna是的,在下面寫回答 – Dmitry

回答

1

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

謝謝你..它看起來不錯。 – bedna

相關問題