3

我必须将文件发布到远程服务器上的 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 服务器上,我在 files 数组中得到了什么:

Array                                                                                                                    
(                                                                                                                        
    [gamefile] => Array                                                                                                  
        (                                                                                                                
            [name] => image.jpg                                                                                          
            [type] =>                                                                                                    
            [tmp_name] =>                                                                                                
            [error] => 3                                                                                                 
            [size] => 0                                                                                                  
        )                                                                                                                

) 

这意味着我的文件没有到达服务器。请建议我是否做错了什么或确实需要做其他事情。

4

1 回答 1

-1

看一下请求模块。它使执行 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'))
于 2012-11-27T22:23:25.390 回答