Shadowfacts
Shadowfacts

Reputation: 1053

axios equivalent to curl --upload-file

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?

Upvotes: 3

Views: 4239

Answers (1)

sideshowbarker
sideshowbarker

Reputation: 88046

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

Upvotes: 7

Related Questions