我需要从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服务器)。
由于
答案 0 :(得分: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) { ... }