【问题标题】:axios equivalent to curl --upload-fileaxios 相当于 curl --upload-file
【发布时间】:2017-06-30 15:20:39
【问题描述】:

我正在尝试使用他们的public API 将 gif 上传到 Gfycat。

这是在命令行上使用 cURL 完成的:

curl https://filedrop.gfycat.com --upload-file /tmp/name

我尝试使用 axios 将其转换为 Node.js:

axios.post("https://filedrop.gfycat.com", {
    data: fs.createReadStream("/tmp/name")
}).then(console.log).catch(console.log);

但消息出错​​p>

<?xml version="1.0" encoding="UTF-8"?>\n<Error><Code>PreconditionFailed</Code><Message>At least one of the pre-conditions you specified did not hold</Message><Condition>Bucket POST must be of the enclosure-type multipart/form-data</Condition><RequestId>6DD49EB33F41DE08</RequestId><HostId>/wyrORPfBWHZk5OuLCrH9Mohwu33vOUNc6NzRSNT08Cxd8PxSEZkzZdj/awpMU6UkpWghrQ1bLY=</HostId></Error>

打印到控制台。

我的 Node.js 代码与 cURL 命令有何不同?使用 axios 与 cURL 命令的等效代码是什么?

【问题讨论】:

    标签: javascript node.js curl axios


    【解决方案1】:

    需要使用FormaData()可以使用form-data,也可能需要使用concat-stream

    const concat = require("concat-stream")
    const FormData = require('form-data');
    const fd = new FormData();
    const fs = require('fs');
    
    fd.append("hello", "world")
    fd.append("file", fs.createReadStream("/tmp/name"))
    fd.pipe(concat({encoding: 'buffer'}, data => {
      axios.post("https://filedrop.gfycat.com", data, {
        headers: fd.getHeaders()
      })
    }))
    

    信用:https://github.com/mzabriskie/axios/issues/318#issuecomment-277231394

    【讨论】:

    • 我使用的是 Node.js 的 axios,FormData 只用于浏览器中的 axios。
    猜你喜欢
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 2014-05-28
    • 2011-09-07
    • 2023-01-12
    相关资源
    最近更新 更多