Curl POST JSON and upload file

Curl is a command-line tool for transferring data between a local computer and a remote server

2 min read
By myfreax
Curl POST JSON and upload file
Curl POST JSON and upload file

Curl is a command-line tool for transferring data between a local computer and a remote server.

When using curl you can download or upload data using protocols such as HTTP, HTTPS, SCP , SFTP and FTP .

The Curl command is pre-installed on most Linux distributions. To check if your Linux distribution has Curl installed, press the shortcut key CTRL+ALT+Tto open Terminal, type curl and press Enter.

If curl is installed, the system will print curl: try 'curl --help' or 'curl --manual' for more information.

Install Curl

Otherwise, the terminal prints the message curl command not found. If you don't have Curl installed, you can install it using your distribution's package manager.

If your computer is running a Debian-based Linux distribution such as Ubuntu, Linux Mint, etc. Please run sudo apt install curl to install Curl.

If your computer is running a Redhat-based Linux distribution, such as CentOS, Fedora, etc. Please run sudo yum install curl to install Curl.

sudo yum install curl
sudo apt install curl

POST JSON and upload the file

When sending JSON data and uploading files to the server, you need to set the Content-Type of the header to multipart/mixed to instruct the Curl command to send data in a mixed format.

In addition to setting the Content-Type of the header, sending JSON format data is to specify the JSON string to be sent with the -F option of the Curl command. Note that JSON needs to be escaped with single quotes.

So the final form of the command is curl -X POST -H "Content-Type: multipart/mixed" -F blob=@file path -F 'metadata=JSON string;type=application/json' .

curl -X POST -H "Content-Type: multipart/mixed" -F "blob=@/Users/username/Documents/bio.jpg" -F "metadata={\"edipi\":123456789};type=application/json" http://localhost:8080/api/v1/user/

upload files only

To upload a file using the Curl command, just use the -F option of the Curl command to specify the multipart MIME data in the form of name=content key-value pairs.

But when specifying a file with the -F option, @ symbols need to be added before the file path . Files can be any type of file including images, documents, etc.

For example, the parameter -F 'image=@/home/user/Pictures/wallpaper.jpg' specifies that the Key is image, and the file is /home/user/Pictures/wallpaper.jpg.

curl -X POST -F 'image=@/home/user/Pictures/wallpaper.jpg' http://example.com/upload
Linux Curl Command Detailed Tutorial | myfreax
curl is a command-line tool for transferring data between a local computer and a remote server
Linux Curl Command Detailed Tutorial

Related Articles