使用curl来发布多部分/表单数据、文件和大量键值对

car*_*mom 3 forms post json curl

作为模拟应用程序前端在后端工作时将执行的操作的一部分,我一直在运行各种curl 命令。很容易只获取要发送的文件Content-Type:application/octet-stream或仅发送 jsonContent-Type:application/json

我发送了 json 内联:

curl -X POST -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://127.0.0.1:8088
Run Code Online (Sandbox Code Playgroud)

从文件中提取 json 并按如下方式发送:

curl -X POST -H "Content-Type: application/json" -H 'Accept: application/json' --data-binary @test.json http://127.0.0.1:8088
Run Code Online (Sandbox Code Playgroud)

(任何想法“接受”的作用是什么?没有它就不起作用..,解决方案来自这里

仅发送一个文件本身,如下所示:

curl --request POST -H "Content-Type:application/octet-stream"  --data-binary "@photo.jpg"  http://127.0.0.1:8088
Run Code Online (Sandbox Code Playgroud)

带有 json 内联和图片的多部分非常好,如下所示:

curl --verbose --request POST --header "Content-Type:multipart/form-data" --form key1=value1  --form upload=@photo.jpg   http://127.0.0.1:8088
Run Code Online (Sandbox Code Playgroud)

(解决方案来自这里

当我尝试从文件和照片中提取键值对,或者将 json 粘贴到同时上传文件的curl 命令中时,问题就开始了。可以curl说服发送"Content-Type:multipart/form-data"来自文件的键值对来自文件的文件附件吗?

约翰.json

{
  "surname" : "Doe",
  "name" : "John",
  "city" : "Manchester",
  "address" : "5 Main Street",
  "hobbies" : ["painting","lawnbowls"]
}
Run Code Online (Sandbox Code Playgroud)

约翰.jpg

我尝试了一些方法,但它只是给我错误消息:

尝试内联,粘贴到 json 中:

$ curl --verbose --request POST --header "Content-Type:multipart/form-data" --data '{"surname" : "Doe","name" : "John","city" : "Manchester","address" : "5 Main Street", "hobbies" : ["painting","lawnbowls"]}'  --form upload=@john.jpg   http://127.0.0.1:8088
Warning: You can only select one HTTP request method! You asked for both POST 
Warning: (-d, --data) and multipart formpost (-F, --form).
Run Code Online (Sandbox Code Playgroud)

然后我尝试从文件中获取它们,但它也不喜欢这样:

$ curl --verbose --request POST --header "Content-Type:multipart/form-data" --form upload@john.json  --form upload=@john.jpg   http://127.0.0.1:8088
Warning: Illegally formatted input field!
curl: option --form: is badly used here
curl: try 'curl --help' or 'curl --manual' for more information
Run Code Online (Sandbox Code Playgroud)

有什么想法可以让这项工作发挥作用吗?

Bre*_*dly 7

我认为您的方向是正确的,但是查看curl手册页可能会让您走得更远。

选项文档的一些关键要点--form

@ 和 < 之间的区别在于 @ 使文件作为文件上传附加在帖子中,而 < 则创建一个文本字段并仅从文件中获取该文本字段的内容。

所以对于JSON使用<,但是对于图片使用@

我认为您还应该指定每个部分的内容类型,以帮助网络服务器知道如何解析每个部分。虽然它大概对每个领域都有期望。

您还可以通过使用“type=”来告诉curl要使用什么Content-Type,其方式类似于:

curl -F "web=@index.html;type=text/html" example.com
Run Code Online (Sandbox Code Playgroud)

您必须查找 JSON 和 jpeg 的 MIME 类型。

最后要记住的是:This option can be used multiple times.

其中大部分内容只是对 @Tanaike 上面所说内容的回响,但有文档中的更多解释。我建议您更详细地阅读它。


我认为对您的命令最大的抱怨curl是表单的每个部分都有 key upload。这有点模棱两可。JSON一键,图片一键吗?

了解网络服务器对表单中每个字段的期望也非常重要。文件上传和文本字段之间存在很大差异。