mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-10-20 11:29:38 +00:00
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.
35 lines
1.5 KiB
Markdown
35 lines
1.5 KiB
Markdown
---
|
|
title: "C08. POST a File as Raw Binary"
|
|
order: 8
|
|
status: "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
|
|
|
|
```cpp
|
|
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](../c07-multipart-upload).
|