NodeJS:如何通过请求POST发送文件

时间:2014-02-27 07:42:13

标签: ruby node.js

我正在使用REQUEST(https://www.npmjs.org/package/request)通过filepicker发送文件,我似乎无法弄清楚如何。我通过RestClient在ruby中做了这个,它看起来像这样:

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)REQUEST中参数的对应部分是什么(是形式?body?header?)? (2)我们如何访问节点文件系统中的文件,以便它可以在请求中发送(即File.new的副本)?

1 个答案:

答案 0 :(得分: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;
    });
}