Nodejs POST 请求 multipart/form-data

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13797670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:45:36  来源:igfitidea点击:

Nodejs POST request multipart/form-data

formsapinode.jshttppost

提问by giodamelio

I am trying to upload a photo via a POST request with the request module

我正在尝试通过 POST 请求上传照片 request module

According to the readme I should just be able to do this

根据自述文件,我应该能够做到这一点

var r = request.post("http://posttestserver.com/post.php", requestCallback)
var form = r.form()
form.append("folder_id", "0");
form.append("filename", fs.createReadStream(path.join(__dirname, "image.png")));

function requestCallback(err, res, body) {
    console.log(body);
}

The problem is, this doesn't work. I get a reply from the test server saying it dumped 0 post variables.

问题是,这行不通。我收到测试服务器的回复,说它转储了 0 个帖子变量。

I have confirmed that the server is in working condition with this little html page

我已经通过这个小 html 页面确认服务器处于工作状态

<html>
    <body>
        <form action="http://posttestserver.com/post.php?dir=example" method="post" enctype="multipart/form-data">
            File: <input type="file" name="submitted">
            <input type="hidden" name="someParam" value="someValue"/>
            <input type="submit" value="send">
        </form>
    </body>
</html>

So the question is, what am I doing wrong with the request module? Is there a better way to send multipart/form-datawith node?

所以问题是,我在请求模块上做错了什么?有没有更好的方式发送multipart/form-data节点?

采纳答案by giodamelio

After some more research, I decided to use the restler module. It makes the multipart upload really easy.

经过更多研究,我决定使用restler module. 它使分段上传非常容易。

fs.stat("image.jpg", function(err, stats) {
    restler.post("http://posttestserver.com/post.php", {
        multipart: true,
        data: {
            "folder_id": "0",
            "filename": restler.file("image.jpg", null, stats.size, null, "image/jpg")
        }
    }).on("complete", function(data) {
        console.log(data);
    });
});

回答by ianmetcalf

So I just got done wrestling with this myself and here is what I learned:

所以我刚刚完成了自己的努力,这是我学到的:

It turns out that neither request or form-data are setting the content-length header for the generated body stream.

事实证明,请求或表单数据都没有为生成的正文流设置内容长度标头。

Here is the reported issue: https://github.com/mikeal/request/issues/316

这是报告的问题:https: //github.com/mikeal/request/issues/316

The solution posted by @lildemongets around this by:

@lildemon发布的解决方案通过以下方式解决了这个问题:

  1. Generating the FormData object
  2. Getting it's length
  3. Making the request and setting the form object and content-length header explicitly
  1. 生成 FormData 对象
  2. 得到它的长度
  3. 发出请求并明确设置表单对象和内容长度标头

Here is a modified version of your example:

这是您的示例的修改版本:

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

var form = new FormData();
form.append("folder_id", "0");
form.append("filename", fs.createReadStream(path.join(__dirname, "image.png")));

form.getLength(function(err, length){
  if (err) {
    return requestCallback(err);
  }

  var r = request.post("http://posttestserver.com/post.php", requestCallback);
  r._form = form;     
  r.setHeader('content-length', length);

});

function requestCallback(err, res, body) {
  console.log(body);
}

回答by wberry

I have working code that does exactly what your question states, with one exception. My file content is appended this way:

我的工作代码完全符合您的问题所述,只有一个例外。我的文件内容以这种方式附加:

form.append('file', new Buffer(...),
    {contentType: 'image/jpeg', filename: 'x.jpg'});

To discover the final options argument I had to drill down into the source of form-data. But this gives me a working configuration. (Maybe it was what you were missing, but of course that will depend on the server.)

为了发现最终的选项参数,我必须深入到form-data. 但这给了我一个工作配置。(也许这是您缺少的东西,但这当然取决于服务器。)

回答by Miroslaw Dylag

I tried also request and form-data modules and was unable to upload a file. You can use superagent which works:

我还尝试了请求和表单数据模块,但无法上传文件。您可以使用有效的超级代理:

http://visionmedia.github.io/superagent/#multipart-requests.

http://visionmedia.github.io/superagent/#multipart-requests

var request = require('superagent');
var agent1 = request.agent();
agent1.post('url/fileUpload')
      .attach('file',__dirname + "/test.png")
      .end(function(err, res) {
          if (err) {
              console.log(err)
           }
       });

回答by Gautam

Try request module. It works like any other normal post request

尝试请求模块。它的工作方式与任何其他正常的发布请求一样

var jsonUpload = {  };
var formData = {
    'file': fs.createReadStream(fileName),
    'jsonUpload': JSON.stringify(jsonUpload)
};
var uploadOptions = {
    "url": "https://upload/url",
    "method": "POST",
    "headers": {
        "Authorization": "Bearer " + accessToken
    },
    "formData": formData
}
var req = request(uploadOptions, function(err, resp, body) {
    if (err) {
        console.log('Error ', err);
    } else {
        console.log('upload successful', body)
    }
});