Files
cpp-httplib/docs-src/pages/ja/cookbook/c11-progress-callback.md
yhirose c95d799180 Polish the wording of the updated docs pages
Reword the Japanese sentences so they read naturally, and correct the
size of the llama.cpp server sources in the code reading chapter.
2026-10-08 20:39:13 -04:00

2.4 KiB

title, order, status
title order status
C11. 進捗コールバックを使う 11 draft

ダウンロードやアップロードの進捗を表示したいときは、DownloadProgressまたはUploadProgressコールバックを渡します。どちらも(current, total)の2引数を取る関数オブジェクトです。

ダウンロードの進捗

httplib::Client cli("http://localhost:8080");

auto res = cli.Get("/large-file",
  [](size_t current, size_t total) {
    auto percent = (total > 0) ? (current * 100 / total) : 0;
    std::cout << "\rDownloading: " << percent << "% ("
              << current << "/" << total << ")" << std::flush;
    return true; // falseを返すとダウンロードを中止
  });
std::cout << std::endl;

コールバックはデータを受信するたびに呼ばれます。totalはContent-Lengthの値です。chunked転送のようにContent-Lengthのないレスポンスでは、進捗コールバックは一度も呼ばれません。

アップロードの進捗

アップロード側も同じ形です。Post()やPut()の最後の引数にUploadProgressを渡します。

httplib::Client cli("http://localhost:8080");

std::string body = load_large_body();

auto res = cli.Post("/upload", body, "application/octet-stream",
  [](size_t current, size_t total) {
    auto percent = current * 100 / total;
    std::cout << "\rUploading: " << percent << "%" << std::flush;
    return true;
  });
std::cout << std::endl;

中断する

コールバックからfalseを返すと、転送を中止できます。UI側で「キャンセル」ボタンが押されたらfalseを返す、といった使い方ができます。

std::atomic<bool> cancelled{false};

auto res = cli.Get("/large-file",
  [&](size_t current, size_t total) {
    return !cancelled.load();
  });

Note: Content-Lengthのないレスポンスでは進捗コールバックが呼ばれないため、この方法は使えません。代わりにContentReceiverからfalseを返して中断します。

Note: ContentReceiverと進捗コールバックは同時に使えます。ファイルに書き出しながら進捗を表示したいときは、両方を渡しましょう。

ファイル保存と組み合わせる具体例はC01. レスポンスボディを取得する / ファイルに保存するも参照してください。