Files
cpp-httplib/docs-src/pages/en/cookbook/c08-post-file-body.md
T
yhirose 9bfd2ddf1c Fix README and docs pages that no longer match the code
Bring the READMEs and the docs pages (en and ja) in line with the
current header:

- Fix the client sample that does not compile, the Transfer-Encoding
  statement for default headers, the verifier callback comment, the
  thread pool spawn rule, the sanitize_filename description, and the
  inverted Accept-Encoding sentence.
- Describe recent behaviour: TLS errors behind Read/Write failures,
  Host validation, Connection: close for a body without length,
  content_reader rules, refused CONNECT, WebSocketClient proxies,
  CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT, the SSE event size limit, and
  the payload limit of the Stream API.
- Complete the API references of WebSocket, WebSocketClient and the
  stream:: helpers, and the SSE reconnect rules.
- Fix cookbook pages: keychain loading on every backend, received Close
  status, a multipart sample that trusted the client's file name, an
  echo sample that sent binary as text, SNI, pre-request handler scope,
  stop() with WebSocket handlers, and the thread pool notes.
- Restore the mutex in the LLM app's Chapter 5 code.
2026-10-18 10:13:57 -04:00

1.5 KiB

title, order, status
title order status
C08. POST a File as Raw Binary 8 draft

Sometimes you want to send a file's contents as the request body directly — no multipart wrapping. This is common for S3-compatible APIs or endpoints that take raw image data. For this, use make_file_body().

Basic usage

httplib::Client cli("https://storage.example.com");

auto [size, provider] = httplib::make_file_body("backup.tar.gz");
if (!provider) {
  std::cerr << "Failed to open file" << std::endl;
  return 1;
}

auto res = cli.Put("/bucket/backup.tar.gz", size,
                   provider, "application/gzip");

make_file_body() returns a pair of file size and a ContentProvider. Pass them to Post() or Put() and the file contents flow straight into the request body.

The ContentProvider reads the file in chunks, so even huge files never sit fully in memory.

When the file can't be opened

If the file can't be opened, make_file_body() returns size as 0 and provider as an empty function object. Sending that would upload an empty body — always check provider first. Checking size won't do: an empty file also gives 0, with a working provider.

Warning: make_file_body() needs to fix the Content-Length up front, so it reads the file size ahead of time. If the file size might change mid-upload, this API isn't the right fit.

To send the file as multipart form data instead, see C07. Upload a file as multipart form data.