How to Send Binary Data with Curl
Sending binary data, such as images, compressed archives, or PDF
files, is a frequent requirement when interacting with REST APIs using
curl. This article explains how to transmit raw binary
payloads using the --data-binary option, ensuring that the
data is sent exactly as-is without any modification or corruption during
transit.
To send binary data in a curl request, the most reliable
method is to use the --data-binary flag combined with the
@ symbol to reference a local file. Unlike the standard
-d or --data options, which can strip carriage
returns or modify newlines, --data-binary processes the
file byte-for-byte.
The Basic Command Syntax
The basic syntax for sending a binary file is as follows:
curl -X POST --data-binary "@path/to/file.ext" https://example.com/api/uploadIn this command: * -X POST specifies the HTTP method
(typically POST or PUT). * --data-binary "@filename" tells
curl to read the specified file as raw binary data. The
@ symbol is critical; without it, curl will
treat the filename string itself as the text payload.
Setting the Correct Content-Type Header
When sending binary data, you must inform the receiving server of the
data’s format using the Content-Type header. You can do
this with the -H flag.
For a generic binary stream:
curl -X POST -H "Content-Type: application/octet-stream" --data-binary "@document.pdf" https://example.com/apiFor a specific format, like a PNG image:
curl -X POST -H "Content-Type: image/png" --data-binary "@image.png" https://example.com/api/uploadSending Binary Data via Multipart Form-Data
If the receiving API expects the file as part of a multipart form
(similar to a standard file upload field on a webpage), use the
-F (or --form) flag instead of
--data-binary. This automatically handles the boundary
headers and binary transmission:
curl -X POST -F "file=@photo.jpg" https://example.com/api/uploadUsing these options ensures your binary payloads are transmitted safely and accurately to the destination server.