File 远程服务器上的php api节点js post文件
我必须将一个文件发布到远程服务器上的PHPAPI url。 我正在创建一个http.request,然后尝试通过从filestream管道将文件数据写入此请求,如下所示:File 远程服务器上的php api节点js post文件,file,node.js,post,File,Node.js,Post,我必须将一个文件发布到远程服务器上的PHPAPI url。 我正在创建一个http.request,然后尝试通过从filestream管道将文件数据写入此请求,如下所示: var req = http.request( options, function(response) { response.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); var fs = require('fs'); var b
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
)
)
这意味着我的文件没有到达服务器。
如果我做错了什么,或者确实需要做其他事情,请给出建议。查看模块。它使得执行REST请求非常容易,包括执行包含文件的POST请求。有关更多信息,请参阅。基本上是这样的:
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'))
谢谢你的回复,查理!!现在,当我使用这种方法时,它会询问我的内容长度。如何发送内容长度if(file!=''){var fs=require('fs');for(var key in args){form.append(key,args[key]);}form.append('json','show');form.append('my_buffer',new buffer(10));form.append('gamefile',fs.createReadStream('/appsoma_workspace/private/ksaini/test.png');form.pipe(req)}-@Charlie key