2014-02-27 69 views
0

我正在使用请求(https://www.npmjs.org/package/request)通过filepicker发送文件,我似乎无法弄清楚如何。我没有通过RESTClient实现这个早在红宝石,它看起来像这样:NodeJS:如何通过请求发送文件POST

response = RestClient.post "https://www.filepicker.io/api/store/S3?key=#{@api_key}", 
    { fileUpload: File.new(zip_path), mimetype: 'application/zip', 
    filename: "filename.zip", multipart:true, access: 'public'} 

我有这样两个问题:(1)什么是参数的请求对方(被它形成体接头??? )? (2)我们如何访问节点文件系统中的文件,以便它可以在请求中发送(即与File.new相对应)?

+0

相同的问题在这里回答http://stackoverflow.com/questions/17218506/file-upload-to-a-node-js-server –

+0

嗯我认为这可能是不同的。我没有尝试将文件上传到我自己的服务器,但试图将请求发送到其中包含文件的另一台服务器。 –

+0

您是否尝试过restler或node-rest-client?它们与ruby restclient类似。 –

回答

1

我在排序时遇到了一些麻烦。也许我错过了一些东西,但看起来工作起来异常复杂。它涉及直接使用form-data模块(有趣的是,请求依赖于)。

问题的根源在于确保包含所有文件数据的表单在调用之前可用于上载请求。我终于跟着the advice one user offered in the issue comments;我创建的形式第一(而不是使用由请求模块自动创建的版本),然后更新请求对象使用的形式:

这是我最后与去解决方案的精简版:

var FormData = require('form-data'); 
var request = require('request'); 

function upload(filepath, url, cb) { //cb(error) 

    // Create the form with your file's data appended FIRST 
    var form = new FormData(); 
    form.append('file', fs.createReadStream(filepath)); 

    // Needed to set the Content-Length header value 
    form.getLength(function(err,length) { 

     var opts = { 
      headers: { 
       'Content-Length': length 
      } 
     }; 

     // Create the request object 
     var r = request.post(url, opts, function(error, res, body) { 

      /* 

      Do things... 

      */ 

      cb(error); 
     }); 

     // Explicitly set the request's form property to 
     // the form you've just created (not officially supported) 
     r._form = form; 
    }); 
} 
+0

我也使用这个解决方案。谢谢! –