axios 相当于 curl --upload-file [英] axios equivalent to curl --upload-file

查看:25
本文介绍了axios 相当于 curl --upload-file的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用他们的 公共 API.

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

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

This is done using cURL on the command line with:

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

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

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);

但是消息有错误

<?xml version="1.0" encoding="UTF-8"?>
<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 命令的等效代码是什么?

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

推荐答案

需要使用 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

这篇关于axios 相当于 curl --upload-file的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆