【问题标题】:cURL request in node.jsnode.js 中的 cURL 请求
【发布时间】:2019-02-08 13:18:06
【问题描述】:

谁能帮我弄清楚如何转换以下请求:

curl -F media=@image.jpg <url>

最好是一个 axios 请求。

【问题讨论】:

  • 这是一个 multipart/form-data 编码的 POST 请求,包括一个图像,只需使用 axios.post() 并将标题和图像添加为 FormData 对象
  • 您能否告诉我 FormData 对象中的图像应该是什么,因为我已经尝试了一些方法,但它们不起作用。我还将标题设置为 { 'Content-Type': 'multipart/form-data' } 我认为这是正确的。

标签: javascript node.js curl axios child-process


【解决方案1】:

我最终使用了child_process

这是一个示例代码:

const childProcess = require('child_process');
[...]

const output = childProcess
    //filePath is "image.jpg"; url is the link where the image will be uploaded
    .execSync(`curl -F media=@${filePath} "${url}"`)
    .toString('utf8');

const response = JSON.parse(output);

【讨论】:

    【解决方案2】:

    您是否正在寻找这样的东西:

    axios.put(url, imageFile, {
    headers: {
    'Content-Type': imageFile.type
    });
      .then(function(response) {
       //Handle success.
    });
      .catch(function (error) {
       //Handle errors.
    });
    

    【讨论】:

    • “类似这样的东西”,可能,但这不会发送图像
    • 不,我要上传图片而不是下载图片
    • 我可能应该对此发表评论而不是发布答案,但我没有 50 名声望,所以我想也许他可以从这里弄清楚 :)
    猜你喜欢
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 2018-06-07
    • 2017-10-31
    • 2014-07-01
    • 2016-05-11
    • 2012-08-31
    • 1970-01-01
    相关资源
    最近更新 更多