Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Post Files and JSON Data Together With Curl?

I've been posting a file with this curl command:

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

Now I want to send some information about the file (as JSON) along with the file.

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 is very grumpy about being used in this completely incorrect way, and in this case it says "You can only select one HTTP request!" OK, fair enough, so how do I get the file attachment and those POST variables into a single curl HTTP request?

like image 990
Jason Champion Avatar asked Feb 22 '14 01:02

Jason Champion


People also ask

Can you post to a JSON file?

Send JSON Data from the Client Side Use JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable.

How do I send multiple files using Curl command?

To post a file with Curl, use the -d or -F command-line options and start the data with the @ symbol followed by the file name. To send multiple files, repeat the -F option several times.


1 Answers

I've had success developing similar endpoints that accept multiple files along with their metadata in JSON format.

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\":\"[email protected]\"};type=application/json" http://localhost:8080/api/v1/user/

Notice the addition of ;type=application/json at the end of the metadata request part. When uploading multiple files of different types, you can define the mime type at the end of the -F value.

I have confirmed that this works for Spring MVC 4.3.7 using @RequestPart. The key in that instance is to not provide the consumes value on the @RequestMapping annotation.

like image 119
Dayel Ostraco Avatar answered Sep 22 '22 22:09

Dayel Ostraco