问题
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 can use form-data and may also need to use concat-stream: FormaData()
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