axios equivalent to curl --upload-file

梦想的初衷 提交于 2021-02-08 07:36:46

问题


I'm trying to upload a gif to Gfycat using their public API.

This is done using cURL on the command line with:

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

I attempted to convert this to Node.js using axios:

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

but an error with the message

<?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>

is printed to the console.

How my Node.js code different than the cURL command and what would be the equivalent code using axios to the cURL command?


回答1:


You need to use FormaData() can use form-data and may also need to use 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()
  })
}))

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



来源:https://stackoverflow.com/questions/42190516/axios-equivalent-to-curl-upload-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!