[英]Post form with file using Node.js
There is an external (I can't change it) API for creating articles. 有一个用于创建文章的外部(我无法更改)API。 Using this API I succeed create an article this way:
使用此API,我成功以这种方式创建了一篇文章:
curl -F "article[id]=607822" -F "article[file]=@/article_file_example/article" 'https://api/v2/articles'
How can I perform this following http request using Node.js (preferably with axios)? 如何使用Node.js(最好是axios)在http请求之后执行此操作?
The code should work for both Linux and Windows, so I can't use require('child_process').exec 该代码对于Linux和Windows均适用,因此我不能使用require('child_process')。exec
I tried the following: 我尝试了以下方法:
const formData = {
'id': 607822,
file: fs.createReadStream(filePath), //filePath is the absolute path to the file
};
axios.post('https://api/v2/articles', {article: formData});
But the API response is validation error, which means I didn't succeed to imitate the curl command. 但是API响应是验证错误,这意味着我没有成功模仿curl命令。
Any suggestions? 有什么建议么?
PS There is also an impovement I would like to perform once I have a working solution. PS:一旦有了可行的解决方案,我也想做一个改进。 I have the file content, so I prefer to send it directly without creating the file + createReadStream.
我有文件内容,因此我更喜欢直接发送而不创建文件+ createReadStream。 I tried to do that Blobing the context, but didn't succeed.
我试图做到这一点Blobing上下文,但没有成功。
Looks like axios doesn't support sending multipart/form-data: https://github.com/mzabriskie/axios/issues/789 看起来axios不支持发送multipart / form-data: https : //github.com/mzabriskie/axios/issues/789
My solution was based on one of the answers for: Nodejs POST request multipart/form-data 我的解决方案基于以下答案之一: Node.js POST请求multipart / form-data
I used restler
module. 我使用了
restler
模块。
I couldn't send my data just as: 我不能像下面那样发送数据:
{
article: {
'id': 607822,
file: restler.file(filePath, null, stats.size, null, "text/plain")
}
}
since it wasn't retrieved correctly by server. 因为服务器未正确检索到它。
So I had to transform it to: 所以我不得不将其转换为:
{
'article[id]': 607822,
'article[file]': restler.file(filePath, null, stats.size, null, "text/plain")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.