我必须将文件发布到远程服务器上的php api url。 我正在创建一个http.request,然后尝试通过从文件流中管道将文件数据写入此请求,如下所示:
var req = http.request( options, function(response) {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
var fs = require('fs');
var boundaryKey = "5JtsIWpXzRoEIdPqkQiSWv4Tl8Bmq";//Math.random().toString(16); // random string
var filelen = filelen; \\Already calculated before
req.setHeader('Content-Type', 'multipart/form-data;boundary='+boundaryKey);
req.setHeader('Content-Length', filelen);
// the header for the one and only part (need to use CRLF here)
req.write('--' + boundaryKey + '\r\n'
// "name" is the name of the form field
// "filename" is the name of the original file
+ 'Content-Disposition: form-data; name="gamefile"; filename="image.jpg"\r\n'
// use your file's mime type here, if known
+ 'Content-Type: image/jpeg\r\n'
+ 'Content-Transfer-Encoding: binary_file_data\r\n\r\n'
);
var fileStream = fs.createReadStream('/image.jpg');
fileStream.pipe(req, { end: false }); // maybe write directly to the socket here?
fileStream.on('end', function() {
console.log("File Streamed");
// mark the end of the one and only part
req.end('--' + boundaryKey + '--\r\n\r\n');
});
在我的php服务器上我得到的文件数组:
Array
(
[gamefile] => Array
(
[name] => image.jpg
[type] =>
[tmp_name] =>
[error] => 3
[size] => 0
)
)
表示我的文件未到达服务器。 如果我做错了或者需要做其他事情,请建议。
答案 0 :(得分:-1)
查看Request模块。它使REST请求变得非常简单,包括执行包含文件的POST请求。有关详细信息,请查看Forms documentation。基本上它就像:
var request = require('request');
var r = request.post('http://service.com/upload')
var form = r.form()
form.append('my_field', 'my_value')
form.append('my_buffer', new Buffer([1, 2, 3]))
form.append('my_file', fs.createReadStream(path.join(__dirname, 'doodle.png'))
form.append('remote_file', request('http://google.com/doodle.png'))