如何与Curl一起发布文件和JSON数据?

时间:2014-02-22 01:08:14

标签: json post file-upload curl curl-commandline

我一直在用这个curl命令发布一个文件:

curl -i -F file=@./File.xlsm -F name=file -X POST http://example.com/new_file/

现在我想发送一些关于文件的信息(作为JSON)以及文件。

curl -i -H "Content-Type: application/json" -d '{"metadata": {"comment": "Submitting a new data set.", "current": false }, "sheet": 1, "row": 7 }' -F file=@./File.xlsm -F name=file http://example.com/new_file/

Curl对于以完全不正确的方式使用非常脾气暴躁,在这种情况下,它说“你只能选择一个HTTP请求!”好的,公平的,那么如何将文件附件和那些POST变量放到一个curl HTTP请求中呢?

4 个答案:

答案 0 :(得分:9)

我已经成功开发了类似的端点,这些端点接受多个文件及其JSON格式的元数据。

curl -i -X POST -H "Content-Type: multipart/mixed" -F "blob=@/Users/username/Documents/bio.jpg" -F "metadata={\"edipi\":123456789,\"firstName\":\"John\",\"lastName\":\"Smith\",\"email\":\"john.smith@gmail.com\"};type=application/json" http://localhost:8080/api/v1/user/

请注意在元数据请求部分的末尾添加了;type=application/json。上传不同类型的多个文件时,可以在-F值的末尾定义mime类型。

我已经确认这适用于使用@RequestPart的Spring MVC 4.3.7。该实例中的关键是不在@RequestMapping注释上提供消耗值。

答案 1 :(得分:4)

您可以添加另一个表单字段:

curl -X POST http://someurl/someresource -F upload=@/path/to/some/file -F data="{\"test\":\"test\"}"

注意:由于内容类型的原因,这并不等同于将json发送到Web服务。

答案 2 :(得分:1)

这对我有用:

curl -v -H "Content-Type:multipart/form-data" -F "meta-data=@C:\Users\saurabh.sharma\Desktop\test.json;type=application/json" -F "file-data=@C:\Users\saurabh.sharma\Pictures\Saved Pictures\windows_70-wallpaper.jpg" http://localhost:7002/test/upload

test.json有我要发送的json数据。

答案 3 :(得分:0)

@nbrooks 注释中,通过在您的 curl中使用几个-H or --header标志,添加一个附加的HTTP头效果很好,如下所示strong>命令:


curl -H "comment: Submitting a new data set." -H  "current: false" -H "sheet: 1" -H "row: 7" -F file=@./File.xlsm -F name=file http://example.com/new_file/

commentcurrent可以合并到“元数据” 在Flask Web服务器上进行request.headers处理。