Study · Advanced · HTTP/1.1

Nhận tệp lớn qua multipart streaming

Gửi một trường tệp từ form. Server ghi từng phần xuống đĩa và chỉ lưu tệp khi toàn bộ request hoàn tất.

Quay lại bài multipart cho form nhỏ

Chọn ngôn ngữ

Tạo thư mục mới, chạy một server trên 127.0.0.1:8080, rồi mở terminal thứ hai ở cùng thư mục. Nhấn Enter trong terminal của server để dừng.

C / C++ · SDK 2.3.0

Chuẩn bị môi trường và cài gói chính thức.

Dùng pkg-config và GMime như bài trước. CMake tự tải phiên bản cố định của thư viện đọc multipart và kiểm tra SHA-256. Lưu 5 tệp vào cùng thư mục.

Tệp dùng chung
CMakeLists.txt
cmake_minimum_required(VERSION 3.24)
project(coakka_multipart_stream LANGUAGES C CXX)

find_package(CoAkkaHttpHost 2.3.0 EXACT CONFIG REQUIRED)
find_package(PkgConfig REQUIRED)
pkg_check_modules(GMime REQUIRED IMPORTED_TARGET gmime-3.0)
include(FetchContent)
FetchContent_Declare(form_parser
  URL https://codeload.github.com/iafonov/multipart-parser-c/tar.gz/772639cf10db6d9f5a655ee9b7eb20b815fab396
  URL_HASH SHA256=40024925c5832b7496e3077e7ec67b210678d479dd9221cc3ddb7fb8006dadb1
  DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
FetchContent_MakeAvailable(form_parser)
add_library(form-parser STATIC "${form_parser_SOURCE_DIR}/multipart_parser.c")
target_include_directories(form-parser PUBLIC "${form_parser_SOURCE_DIR}")

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_library(upload-handler STATIC upload.c)
target_link_libraries(upload-handler PUBLIC CoAkkaHttp::host PkgConfig::GMime form-parser)
add_executable(upload-c main.c)
add_executable(upload-cpp main.cpp)
target_link_libraries(upload-c PRIVATE upload-handler)
target_link_libraries(upload-cpp PRIVATE upload-handler)
foreach(target IN ITEMS upload-handler upload-c upload-cpp)
  target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic -Werror)
endforeach()
upload.h
#ifndef COAKKA_PORTAL_UPLOAD_H
#define COAKKA_PORTAL_UPLOAD_H

#ifdef __cplusplus
extern "C" {
#endif

int run_upload_lab(void);

#ifdef __cplusplus
}
#endif
#endif
upload.c
#define _POSIX_C_SOURCE 200809L

#include "upload.h"
#include <coakka/http/host.h>
#include <errno.h>
#include <gmime/gmime.h>
#include <multipart_parser.h>
#include <poll.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>

enum {
  FILE_LIMIT = 2 * 1024 * 1024,
  BODY_LIMIT = FILE_LIMIT + 16 * 1024,
  HEADER_LIMIT = 4096,
  MAX_UPLOADS = 8
};

typedef struct {
  coakka_http_host_exchange_t id;
  multipart_parser *parser;
  FILE *file;
  char path[sizeof("uploads/incoming-XXXXXX")];
  char field[65];
  char value[HEADER_LIMIT + 1];
  size_t field_size, value_size, header_bytes;
  size_t received, saved;
  unsigned failure;
  bool active, in_value, part_started, valid_field, form_ended;
} Upload;

static coakka_http_host_bytes_t bytes(const char *value) {
  return (coakka_http_host_bytes_t){(const uint8_t *)value, strlen(value)};
}

static bool check(coakka_http_host_status_t status, const char *step) {
  if (status == COAKKA_HTTP_HOST_OK) {
    return true;
  }
  fprintf(stderr, "%s: %s\n", step, coakka_http_host_status_name(status));
  return false;
}

static void discard(Upload *upload) {
  if (upload->parser) {
    multipart_parser_free(upload->parser);
  }
  if (upload->file) {
    fclose(upload->file);
  }
  if (upload->path[0] && unlink(upload->path) != 0 && errno != ENOENT) {
    perror("remove partial upload");
  }
  *upload = (Upload){0};
}

static bool accept_header(Upload *upload) {
  if (strcasecmp(upload->field, "content-transfer-encoding") == 0) {
    return false;
  }
  if (strcasecmp(upload->field, "content-disposition") != 0) {
    return true;
  }
  if (upload->valid_field) {
    return false;
  }
  GMimeContentDisposition *header =
      g_mime_content_disposition_parse(NULL, upload->value);
  if (!header) {
    return false;
  }
  const char *kind = g_mime_content_disposition_get_disposition(header);
  const char *name = g_mime_content_disposition_get_parameter(header, "name");
  const char *filename =
      g_mime_content_disposition_get_parameter(header, "filename");
  upload->valid_field = kind && strcasecmp(kind, "form-data") == 0 && name &&
                        strcmp(name, "file") == 0 && filename && *filename;
  g_object_unref(header);
  return upload->valid_field;
}

static int part_start(multipart_parser *parser) {
  Upload *upload = multipart_parser_get_data(parser);
  if (upload->part_started) {
    return 1; // This exercise accepts exactly one part.
  }
  upload->part_started = true;
  return 0;
}

static int header_field(multipart_parser *parser, const char *data,
                        size_t size) {
  Upload *upload = multipart_parser_get_data(parser);
  if (upload->in_value) {
    if (!accept_header(upload)) {
      return 1;
    }
    upload->in_value = false;
    upload->field_size = upload->value_size = 0;
    upload->field[0] = upload->value[0] = '\0';
  }
  if (size > HEADER_LIMIT - upload->header_bytes ||
      size > sizeof(upload->field) - 1U - upload->field_size) {
    return 1;
  }
  memcpy(upload->field + upload->field_size, data, size);
  upload->field_size += size;
  upload->field[upload->field_size] = '\0';
  upload->header_bytes += size;
  return 0;
}

static int header_value(multipart_parser *parser, const char *data,
                        size_t size) {
  Upload *upload = multipart_parser_get_data(parser);
  if (size > HEADER_LIMIT - upload->header_bytes || memchr(data, '\0', size)) {
    return 1;
  }
  upload->in_value = true;
  memcpy(upload->value + upload->value_size, data, size);
  upload->value_size += size;
  upload->value[upload->value_size] = '\0';
  upload->header_bytes += size;
  return 0;
}

static int headers_complete(multipart_parser *parser) {
  Upload *upload = multipart_parser_get_data(parser);
  if (!accept_header(upload) || !upload->valid_field) {
    return 1;
  }
  strcpy(upload->path, "uploads/incoming-XXXXXX");
  const int fd = mkstemp(upload->path);
  if (fd < 0) {
    upload->path[0] = '\0';
  } else {
    upload->file = fdopen(fd, "wb");
    if (!upload->file) {
      close(fd);
    }
  }
  if (!upload->file) {
    upload->failure = 500U;
    return 1;
  }
  return 0;
}

static int file_data(multipart_parser *parser, const char *data, size_t size) {
  Upload *upload = multipart_parser_get_data(parser);
  if (size > FILE_LIMIT - upload->saved) {
    upload->failure = 413U;
    return 1;
  }
  if (size && fwrite(data, 1U, size, upload->file) != size) {
    upload->failure = 500U;
    return 1;
  }
  upload->saved += size;
  return 0;
}

static int form_end(multipart_parser *parser) {
  Upload *upload = multipart_parser_get_data(parser);
  upload->form_ended = true;
  return 0;
}

static multipart_parser *new_parser(coakka_http_host_bytes_t type) {
  static const multipart_parser_settings settings = {
      .on_part_data_begin = part_start,
      .on_header_field = header_field,
      .on_header_value = header_value,
      .on_headers_complete = headers_complete,
      .on_part_data = file_data,
      .on_body_end = form_end,
  };
  if (!type.size || type.size > 1024U || memchr(type.data, '\0', type.size)) {
    return NULL;
  }
  char text[1025];
  memcpy(text, type.data, type.size);
  text[type.size] = '\0';
  GMimeContentType *media = g_mime_content_type_parse(NULL, text);
  if (!media) {
    return NULL;
  }
  multipart_parser *parser = NULL;
  const char *boundary = g_mime_content_type_get_parameter(media, "boundary");
  if (g_mime_content_type_is_type(media, "multipart", "form-data") &&
      boundary && *boundary && strlen(boundary) <= 70U &&
      !strpbrk(boundary, "\r\n")) {
    char delimiter[73];
    snprintf(delimiter, sizeof(delimiter), "--%s", boundary);
    parser = multipart_parser_init(delimiter, &settings);
  }
  g_object_unref(media);
  return parser;
}

static coakka_http_host_bytes_t
content_type(const coakka_http_host_request_event_t *event) {
  const uint32_t count = coakka_http_host_request_header_count(event);
  for (uint32_t index = 0; index < count; ++index) {
    coakka_http_host_header_t header = {0};
    if (coakka_http_host_request_header(event, index, &header) &&
        header.name.size == sizeof("content-type") - 1U &&
        strncasecmp((const char *)header.name.data, "content-type",
                    header.name.size) == 0) {
      return header.value;
    }
  }
  return (coakka_http_host_bytes_t){0};
}

static void feed(Upload *upload, coakka_http_host_bytes_t chunk) {
  if (chunk.size > BODY_LIMIT - upload->received) {
    upload->failure = 413U;
    return;
  }
  upload->received += chunk.size;
  if (!upload->failure && !upload->form_ended) {
    const size_t consumed = multipart_parser_execute(
        upload->parser, (const char *)chunk.data, chunk.size);
    if (consumed != chunk.size && !upload->failure && !upload->form_ended) {
      upload->failure = 400U;
    }
  }
}

static unsigned finish(Upload *upload) {
  if (upload->failure) {
    return upload->failure;
  }
  if (!upload->form_ended || !upload->file) {
    return 400U;
  }
  const int closed = fclose(upload->file);
  upload->file = NULL;
  if (closed != 0 || rename(upload->path, "uploads/streamed.bin") != 0) {
    return 500U;
  }
  upload->path[0] = '\0';
  return 201U;
}

static Upload *lookup(Upload *uploads, coakka_http_host_exchange_t id) {
  for (size_t index = 0; index < MAX_UPLOADS; ++index) {
    Upload *upload = &uploads[index];
    if (upload->active && upload->id.slot == id.slot &&
        upload->id.generation == id.generation) {
      return upload;
    }
  }
  return NULL;
}

static bool take_upload(coakka_http_host_service_t *service, Upload *uploads) {
  coakka_http_host_request_event_t event;
  coakka_http_host_request_event_init(&event);
  const coakka_http_host_status_t received =
      coakka_http_host_take_request(service, 500U, &event);
  if (received == COAKKA_HTTP_HOST_TIMEOUT) {
    return true;
  }
  if (!check(received, "read event")) {
    return false;
  }
  const coakka_http_host_exchange_t id = event.exchange;
  Upload *upload = lookup(uploads, id);
  unsigned status = 0;
  size_t saved = 0;
  if (event.kind == COAKKA_HTTP_HOST_REQUEST) {
    for (size_t index = 0; index < MAX_UPLOADS; ++index) {
      if (!uploads[index].active) {
        upload = &uploads[index];
        upload->id = id;
        upload->active = true;
        upload->parser = new_parser(content_type(&event));
        if (upload->parser) {
          multipart_parser_set_data(upload->parser, upload);
        } else {
          upload->failure = 400U;
        }
        break;
      }
    }
  } else if (event.kind == COAKKA_HTTP_HOST_REQUEST_DATA && upload) {
    feed(upload, event.data);
  } else if (event.kind == COAKKA_HTTP_HOST_REQUEST_END) {
    status = 503U;
    if (upload) {
      saved = upload->saved;
      status = finish(upload);
      discard(upload);
    }
  } else if ((event.kind == COAKKA_HTTP_HOST_REQUEST_CANCELLED ||
              event.kind == COAKKA_HTTP_HOST_REQUEST_TERMINAL) &&
             upload) {
    discard(upload);
  }

  // Parser callbacks finish before the Core-owned input lease is released.
  if (!check(coakka_http_host_release_request(service, &event),
             "release event")) {
    return false;
  }
  if (status) {
    char message[80];
    if (status == 201U) {
      snprintf(message, sizeof(message), "saved streamed.bin (%zu bytes)\n",
               saved);
    } else {
      const char *error =
          status == 413U   ? "multipart upload exceeds its limit\n"
          : status == 400U ? "expected one complete file field\n"
                           : "cannot save upload\n";
      snprintf(message, sizeof(message), "%s", error);
    }
    coakka_http_host_response_t response;
    coakka_http_host_response_init(&response);
    response.status_code = status;
    response.body = bytes(message);
    (void)check(coakka_http_host_respond(service, id, &response), "respond");
  }
  return true;
}

static bool drain(coakka_http_host_service_t *service, Upload *uploads) {
  if (!check(coakka_http_host_service_begin_drain(service), "begin drain")) {
    return false;
  }
  // Keep releasing events as Core finishes in-flight work.
  for (;;) {
    coakka_http_host_drain_state_t state = COAKKA_HTTP_HOST_DRAIN_NOT_STARTED;
    const coakka_http_host_status_t status =
        coakka_http_host_service_wait_drained(service, 0U, &state);
    if (status != COAKKA_HTTP_HOST_TIMEOUT ||
        state != COAKKA_HTTP_HOST_DRAIN_PENDING) {
      return check(status, "finish drain");
    }
    if (!take_upload(service, uploads)) {
      return false;
    }
  }
}

int run_upload_lab(void) {
  if (mkdir("uploads", 0700) != 0 && errno != EEXIST) {
    perror("create uploads");
    return EXIT_FAILURE;
  }
  coakka_http_host_configuration_t config;
  coakka_http_host_configuration_init(&config);
  config.bind_address = bytes("127.0.0.1");
  config.port = 8080;
  config.limits.max_request_body_bytes = BODY_LIMIT;
  config.limits.drain_timeout_ms = 2000U;
  config.limits.stop_timeout_ms = 4000U;

  coakka_http_host_route_t route;
  coakka_http_host_route_init(&route);
  route.route_id = 1U;
  route.handler_binding_id = 1U;
  route.method = bytes("POST");
  route.encoded_path_pattern = bytes("/upload/multipart-stream");
  route.flags |= COAKKA_HTTP_HOST_ROUTE_STREAMING_REQUEST;

  coakka_http_host_service_t *service = NULL;
  uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
  if (!check(coakka_http_host_service_create(&config, &route, 1U, &service,
                                             &failed_route),
             "create service")) {
    return EXIT_FAILURE;
  }
  g_mime_init();
  coakka_http_host_issue_t issue;
  coakka_http_host_issue_init(&issue);
  bool running =
      check(coakka_http_host_service_start(service, &issue), "start");
  Upload uploads[MAX_UPLOADS] = {0};
  if (running) {
    puts("Listening on http://127.0.0.1:8080; press Enter to stop.");
    fflush(stdout);
    struct pollfd input = {.fd = STDIN_FILENO, .events = POLLIN};
    while (running) {
      const int ready = poll(&input, 1U, 0);
      if (ready > 0) {
        break; // Enter or EOF; the same reader will finish draining events.
      }
      if (ready < 0 && errno != EINTR) {
        perror("read stop input");
        running = false;
        break;
      }
      running = take_upload(service, uploads);
    }
    if (running) {
      running = drain(service, uploads);
    }
  }
  for (size_t index = 0; index < MAX_UPLOADS; ++index) {
    discard(&uploads[index]);
  }
  const bool closed = check(coakka_http_host_service_stop(service), "stop");
  const bool destroyed =
      check(coakka_http_host_service_destroy(&service), "destroy");
  g_mime_shutdown();
  return running && closed && destroyed ? EXIT_SUCCESS : EXIT_FAILURE;
}
C · main.c
main.c
#include "upload.h"

int main(void) { return run_upload_lab(); }
C++ · main.cpp
main.cpp
#include "upload.h"

// The C ABI works unchanged inside a C++ application.
int main() { return run_upload_lab(); }
CMake
cmake -S . -B build -DCMAKE_PREFIX_PATH="$COAKKA_HTTP_SDK"
cmake --build build
C
./build/upload-c
C++
./build/upload-cpp
Go · 2.3.2

Chuẩn bị môi trường và cài gói chính thức.

upload.go
upload.go
package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"mime"
	"mime/multipart"
	"os"

	http "github.com/phuong-tran/coakka-http-runtime-go/v2"
)

const fileLimit = 2 * 1024 * 1024
const bodyLimit = fileLimit + 16*1024

func upload(request *http.Request) (http.Response, error) {
	wire := &io.LimitedReader{R: request.Body, N: bodyLimit + 1}
	status, message := 400, "expected one complete file field\n"
	name := ""
	var size int64
	defer func() {
		if name != "" {
			if err := os.Remove(name); err != nil && !os.IsNotExist(err) {
				log.Printf("remove partial upload: %v", err)
			}
		}
	}()

	contentType, _ := request.Headers.Get("content-type")
	kind, params, err := mime.ParseMediaType(contentType)
	boundary := params["boundary"]
	if err == nil && kind == "multipart/form-data" && len(boundary) >= 1 && len(boundary) <= 70 {
		form := multipart.NewReader(wire, boundary)
		part, err := form.NextRawPart()
		if err == nil && part.FormName() == "file" && part.FileName() != "" &&
			part.Header.Get("Content-Transfer-Encoding") == "" {
			file, err := os.CreateTemp("uploads", "incoming-*.part")
			if err != nil {
				status, message = 500, "cannot open temporary file\n"
			} else {
				name = file.Name()
				size, err = io.Copy(file, io.LimitReader(part, fileLimit))
				closeErr := file.Close()
				var extra [1]byte
				if err == nil && closeErr == nil {
					n, readErr := io.ReadFull(part, extra[:])
					if n != 0 {
						status, message = 413, "file exceeds 2 MiB\n"
					} else if readErr == io.EOF {
						if _, err := form.NextRawPart(); err == io.EOF {
							status = 201
						}
					}
				}
			}
		}
	}

	// A closing form delimiter is not the same as HTTP end-of-body.
	// Drain the bounded reader before publishing or replying.
	_, err = io.Copy(io.Discard, wire)
	if wire.N == 0 {
		return http.Text(413, "multipart body exceeds its limit\n")
	}
	if err != nil {
		return http.Text(400, "upload did not complete\n")
	}
	if status != 201 {
		return http.Text(uint32(status), message)
	}
	if err := os.Rename(name, "uploads/streamed.bin"); err != nil {
		return http.Text(500, "cannot publish upload\n")
	}
	return http.Text(201, fmt.Sprintf("saved streamed.bin (%d bytes)\n", size))
}

func run() (err error) {
	if err := os.MkdirAll("uploads", 0700); err != nil {
		return err
	}
	limits := http.DefaultLimits()
	limits.MaxRequestBodyBytes = bodyLimit
	limits.RequestStreamMaxRetainedItems = 32
	server, err := http.NewBuilder().
		Listen("127.0.0.1", 8080).
		Limits(limits).
		PostStream("/upload/multipart-stream", upload).
		Start()
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, server.Close()) }()
	log.Print("Listening on http://127.0.0.1:8080; press Enter to stop.")
	_, _ = os.Stdin.Read(make([]byte, 1))
	return nil
}

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}
Go
go mod init example.com/coakka-multipart-stream
go get github.com/phuong-tran/coakka-http-runtime-go/[email protected]
export CGO_CFLAGS="-I$COAKKA_HTTP_SDK/include"
export CGO_LDFLAGS="-L$COAKKA_HTTP_SDK/lib -Wl,-rpath,$COAKKA_HTTP_SDK/lib"
go run upload.go
Python · 2.3.2

Chuẩn bị môi trường và cài gói chính thức.

upload.py
upload.py
import os
import tempfile
from email.message import Message
from pathlib import Path

from coakka_http import Builder, Limits, Request, Response
from multipart import MultipartSegment, ParserError, ParserLimitReached, PushMultipartParser

FILE_LIMIT = 2 * 1024 * 1024
BODY_LIMIT = FILE_LIMIT + 16 * 1024
UPLOADS = Path("uploads")


def upload(request: Request) -> Response:
    media = Message()
    media["Content-Type"] = request.headers.get("content-type") or ""
    boundary = media.get_param("boundary")
    if media.get_content_type() != "multipart/form-data" or not boundary or len(boundary) > 70:
        return Response.text("expected multipart/form-data with a boundary\n", status=400)

    output = None
    temporary = None
    seen_file = False
    accepted_end = False
    size = total = 0
    status = 0
    try:
        parser = PushMultipartParser(
            boundary, max_header_size=4096, max_segment_size=FILE_LIMIT, max_segment_count=2
        )
        while chunk := request.body_reader.read(8192):
            total += len(chunk)
            if total > BODY_LIMIT:
                return Response.text("multipart body exceeds its limit\n", status=413)
            if status or parser.closed:
                continue
            try:
                for event in parser.parse(chunk):
                    if isinstance(event, MultipartSegment):
                        if seen_file or event.name != "file" or not event.filename:
                            status = 400
                            break
                        seen_file = True
                        output = tempfile.NamedTemporaryFile(
                            dir=UPLOADS, prefix="incoming-", suffix=".part", delete=False
                        )
                        temporary = Path(output.name)
                    elif event is None:
                        accepted_end = True
                    else:
                        output.write(event)
                        size += len(event)
            except ParserLimitReached:
                status = 413
            except ParserError:
                status = 400
        if status == 413:
            return Response.text("multipart file or parser limit exceeded\n", status=413)
        if status or not seen_file or not accepted_end:
            return Response.text("expected one complete file field\n", status=400)
        parser.close(check_complete=True)
        output.close()
        os.replace(temporary, UPLOADS / "streamed.bin")
        return Response.text(f"saved streamed.bin ({size} bytes)\n", status=201)
    except (OSError, ValueError, ParserError) as error:
        print(f"Upload did not complete: {error}", flush=True)
        return Response.text("upload did not complete\n", status=400)
    finally:
        if output is not None:
            try:
                output.close()
            finally:
                temporary.unlink(missing_ok=True)


def main() -> None:
    UPLOADS.mkdir(mode=0o700, exist_ok=True)
    service = (
        Builder()
        .listen("127.0.0.1", 8080)
        .limits(Limits(max_request_body_bytes=BODY_LIMIT, request_stream_max_retained_items=32))
        .post_stream("/upload/multipart-stream", upload)
        .start()
    )
    with service:
        print("Listening on http://127.0.0.1:8080; press Enter to stop.", flush=True)
        input()


if __name__ == "__main__":
    main()
Python
python3 -m venv .venv
. .venv/bin/activate
python -m pip install coakka-http-runtime-python==2.3.2 multipart==2.0.1
python upload.py
Node.js / Bun · 2.3.2

Chuẩn bị môi trường và cài gói chính thức.

upload.mjs
upload.mjs
import { randomUUID } from "node:crypto";
import { closeSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from "node:fs";
import Busboy from "busboy";

const { Builder, Limits, Response } = await import(process.versions.bun
  ? "coakka-http-runtime-bun"
  : "coakka-http-runtime-node");

const FILE_LIMIT = 2 * 1024 * 1024;
const BODY_LIMIT = FILE_LIMIT + 16 * 1024;
const PARSER_QUEUE_LIMIT = 64 * 1024;
const active = new Map();
mkdirSync("uploads", { recursive: true, mode: 0o700 });

function discard(upload) {
  try {
    if (upload.fd !== undefined) {
      const fd = upload.fd;
      upload.fd = undefined;
      closeSync(fd);
    }
  } finally {
    if (upload.path) rmSync(upload.path, { force: true });
  }
}

function writeFile(upload, chunk) {
  if (upload.status) return;
  if (chunk.length > FILE_LIMIT - upload.size) {
    upload.status = 413;
    return;
  }
  try {
    let offset = 0;
    while (offset < chunk.length) {
      const written = writeSync(upload.fd, chunk, offset, chunk.length - offset);
      if (!written) throw new Error("upload write made no progress");
      offset += written;
    }
    upload.size += chunk.length;
  } catch {
    upload.status = 500;
  }
}

function start(request) {
  const upload = { total: 0, size: 0, status: 0, seen: false, fileEnded: false };
  const contentType = request.headers.get("content-type");
  if (!/^multipart\/form-data\s*;/i.test(contentType ?? "")) {
    upload.status = 400;
    return upload;
  }
  try {
    upload.parser = Busboy({
      headers: { "content-type": contentType },
      highWaterMark: PARSER_QUEUE_LIMIT,
      fileHwm: 8192,
      limits: { fileSize: FILE_LIMIT + 1, fields: 1, files: 2, parts: 2 },
    });
  } catch {
    upload.status = 400;
    return upload;
  }
  upload.closed = new Promise((resolve) => upload.parser.once("close", resolve));
  upload.parser.on("error", () => { upload.status ||= 400; });
  upload.parser.on("field", () => { upload.status ||= 400; });
  upload.parser.on("partsLimit", () => { upload.status ||= 400; });
  upload.parser.on("filesLimit", () => { upload.status ||= 400; });
  upload.parser.on("file", (name, file, info) => {
    file.on("error", () => { upload.status ||= 400; });
    if (upload.seen || name !== "file" || !info.filename) {
      upload.status ||= 400;
      file.resume();
      return;
    }
    upload.seen = true;
    try {
      const path = `uploads/incoming-${randomUUID()}.part`;
      upload.fd = openSync(path, "wx", 0o600);
      upload.path = path;
    } catch {
      upload.status = 500;
    }
    file.on("limit", () => { upload.status ||= 413; });
    file.on("data", (chunk) => writeFile(upload, chunk));
    file.on("end", () => { upload.fileEnded = true; });
  });
  return upload;
}

function multipart(event) {
  const id = `${event.id.slot}:${event.id.generation}`;
  if (event.kind === "start") {
    active.set(id, start(event.request));
    return;
  }
  const upload = active.get(id);
  if (!upload) return;
  if (event.kind === "dispose") {
    active.delete(id);
    upload.parser?.destroy();
    discard(upload);
  } else if (event.kind === "data") {
    upload.total += event.data.length;
    if (upload.total > BODY_LIMIT) upload.status = 413;
    if (!upload.status && !upload.parser.destroyed) {
      // Only the end callback may return a value. Bound the parser backlog
      // explicitly; the file callback consumes each chunk synchronously.
      if (upload.parser.writableLength + event.data.length > PARSER_QUEUE_LIMIT) {
        upload.status = 503;
      } else {
        upload.parser.write(event.data, (error) => {
          if (error) upload.status ||= 400;
        });
      }
    }
  } else if (event.kind === "end") {
    return finish(upload);
  }
}

async function finish(upload) {
  if (upload.parser && !upload.parser.destroyed) {
    if (upload.status) upload.parser.destroy();
    else upload.parser.end();
    await upload.closed;
  }
  if (upload.status || !upload.seen || !upload.fileEnded) {
    const status = upload.status || 400;
    const message = status === 413 ? "multipart upload exceeds its limit"
      : status === 500 ? "cannot write upload"
      : status === 503 ? "upload parser is busy" : "expected one complete file field";
    return Response.text(message + "\n", { status });
  }
  try {
    const fd = upload.fd;
    upload.fd = undefined;
    closeSync(fd);
    renameSync(upload.path, "uploads/streamed.bin");
    upload.path = undefined;
    return Response.text(`saved streamed.bin (${upload.size} bytes)\n`, { status: 201 });
  } catch {
    return Response.text("cannot publish upload\n", { status: 500 });
  }
}

const service = new Builder()
  .listen("127.0.0.1", 8080)
  .limits(new Limits({ maxRequestBodyBytes: BODY_LIMIT }))
  .postStream("/upload/multipart-stream", multipart)
  .start();

console.log("Listening on http://127.0.0.1:8080; press Enter to stop.");
try {
  for await (const chunk of process.stdin) {
    if (chunk.length) break;
  }
} finally {
  await service.close();
}
Node.js
npm
npm install --save-exact [email protected] [email protected]
node upload.mjs
Bun
Bun
bun add --exact [email protected] [email protected]
bun upload.mjs
Java / Kotlin · JVM 2.3.2

Chuẩn bị môi trường và cài gói chính thức.

Dùng JDK 17 trở lên. Lưu JavaUpload.java cho cả hai lựa chọn vì Kotlin dùng chung phần xử lý tệp. Lệnh dưới đây chọn gói native cho Pi ARM64; trên macOS ARM64 bỏ tùy chọn chọn nền tảng.

Mã nguồn JVM
src/main/java/study/JavaUpload.java
package study;

import coakka.http.Limits;
import coakka.http.Request;
import coakka.http.Response;
import coakka.http.Responses;
import coakka.http.Service;
import coakka.http.ServiceBuilder;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.ContentDisposition;
import jakarta.mail.internet.ContentType;
import jakarta.mail.internet.InternetHeaders;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.apache.commons.fileupload2.core.MultipartInput;
import org.apache.commons.io.input.BoundedInputStream;

public final class JavaUpload {
    private static final int FILE_LIMIT = 2 * 1024 * 1024;
    static final int BODY_LIMIT = FILE_LIMIT + 16 * 1024;
    static final Path UPLOADS = Path.of("uploads");

    private JavaUpload() {}

    private static final class FileSink extends OutputStream {
        private final OutputStream output;
        private int size;
        private boolean overLimit;

        FileSink(OutputStream output) {
            this.output = output;
        }

        @Override
        public void write(int value) throws IOException {
            if (overLimit || size == FILE_LIMIT) {
                overLimit = true;
            } else {
                output.write(value);
                size++;
            }
        }

        @Override
        public void write(byte[] data, int start, int length) throws IOException {
            if (overLimit || length > FILE_LIMIT - size) {
                overLimit = true;
            } else {
                output.write(data, start, length);
                size += length;
            }
        }
    }

    private static boolean fileField(String headerBlock) throws MessagingException {
        InternetHeaders headers = new InternetHeaders(new ByteArrayInputStream(
                headerBlock.getBytes(StandardCharsets.ISO_8859_1)));
        String raw = headers.getHeader("Content-Disposition", null);
        if (raw == null || headers.getHeader("Content-Transfer-Encoding") != null) {
            return false;
        }
        ContentDisposition disposition = new ContentDisposition(raw);
        String name = disposition.getParameter("filename");
        return "form-data".equalsIgnoreCase(disposition.getDisposition())
                && "file".equals(disposition.getParameter("name")) && name != null && !name.isEmpty();
    }

    static Response upload(Request request) {
        Path temporary = null;
        try {
            BoundedInputStream wire = BoundedInputStream.builder()
                    .setInputStream(request.getBody())
                    .setMaxCount(BODY_LIMIT + 1L)
                    .setPropagateClose(false)
                    .get();
            int status = 400;
            int size = 0;
            try {
                String contentType = request.getHeaders().get("content-type");
                ContentType media = contentType == null ? null : new ContentType(contentType);
                String boundary = media == null ? null : media.getParameter("boundary");
                if (media != null && media.match("multipart/form-data") && boundary != null
                        && !boundary.isEmpty() && boundary.length() <= 70) {
                    MultipartInput parser = MultipartInput.builder()
                            .setInputStream(wire)
                            .setBoundary(boundary.getBytes(StandardCharsets.US_ASCII))
                            .setBufferSize(8192)
                            .setMaxPartHeaderSize(4096)
                            .get();
                    parser.setHeaderCharset(StandardCharsets.ISO_8859_1);
                    if (parser.skipPreamble() && fileField(parser.readHeaders())) {
                        temporary = Files.createTempFile(UPLOADS, "incoming-", ".part");
                        try (OutputStream output = Files.newOutputStream(temporary)) {
                            FileSink sink = new FileSink(output);
                            // The part reader borrows the parser. A failed read
                            // abandons this parser; do not drain from its close.
                            parser.newInputStream().transferTo(sink);
                            size = sink.size;
                            status = sink.overLimit ? 413 : parser.readBoundary() ? 400 : 201;
                        }
                    }
                }
            } catch (MessagingException | MultipartInput.MalformedStreamException error) {
                status = 400;
            }
            // The form can end before the HTTP body ends. Wait for the latter.
            wire.transferTo(OutputStream.nullOutputStream());
            if (wire.getCount() > BODY_LIMIT || status == 413) {
                return Responses.text("multipart upload exceeds its limit\n", 413);
            }
            if (status != 201) {
                return Responses.text("expected one complete file field\n", 400);
            }
            Files.move(temporary, UPLOADS.resolve("streamed.bin"),
                    StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
            return Responses.text("saved streamed.bin (" + size + " bytes)\n", 201);
        } catch (IOException error) {
            System.err.println("Upload did not complete: " + error);
            return Responses.text("upload did not complete\n", 400);
        } finally {
            if (temporary != null) {
                try {
                    Files.deleteIfExists(temporary);
                } catch (IOException error) {
                    System.err.println("Cannot remove temporary upload: " + error);
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Files.createDirectories(UPLOADS);
        Limits limits = new Limits(0, 0, 0, 0, BODY_LIMIT, 0, 0, 0, 0, 0, 32);
        Service server = new ServiceBuilder()
                .listen("127.0.0.1", 8080)
                .limits(limits)
                .postStream("/upload/multipart-stream", JavaUpload::upload)
                .start();
        try {
            System.out.println("Listening on http://127.0.0.1:8080; press Enter to stop.");
            System.in.read();
        } finally {
            server.close();
        }
    }
}
src/main/kotlin/study/KotlinUpload.kt
package study

import coakka.http.Limits
import coakka.http.ServiceBuilder
import java.nio.file.Files

fun main() {
    Files.createDirectories(JavaUpload.UPLOADS)
    val server = ServiceBuilder()
        .listen(host = "127.0.0.1", port = 8080)
        .limits(Limits(maxRequestBodyBytes = JavaUpload.BODY_LIMIT.toLong(), requestStreamMaxRetainedItems = 32))
        .postStream(pattern = "/upload/multipart-stream") { request ->
            JavaUpload.upload(request)
        }
        .start()
    try {
        println("Listening on http://127.0.0.1:8080; press Enter to stop.")
        readlnOrNull()
    } finally {
        server.close()
    }
}
Maven
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>example.coakka</groupId>
  <artifactId>coakka-http-multipart-stream-lab</artifactId>
  <version>1.0.0</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.release>17</maven.compiler.release>
    <kotlin.version>2.3.10</kotlin.version>
    <coakka.version>2.3.2</coakka.version>
    <coakka.target>macos-aarch64</coakka.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>io.github.phuong-tran.coakka</groupId>
      <artifactId>coakka-http-runtime-jvm</artifactId>
      <version>${coakka.version}</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.angus</groupId>
      <artifactId>angus-mail</artifactId>
      <version>2.0.5</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-fileupload2-core</artifactId>
      <version>2.0.0-M5</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-maven-plugin</artifactId>
        <version>${kotlin.version}</version>
        <executions>
          <execution>
            <id>compile-kotlin</id>
            <phase>process-sources</phase>
            <goals><goal>compile</goal></goals>
            <configuration>
              <jvmTarget>17</jvmTarget>
              <args><arg>-Werror</arg><arg>-Xjdk-release=17</arg></args>
              <sourceDirs>
                <sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
                <sourceDir>${project.basedir}/src/main/java</sourceDir>
              </sourceDirs>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.14.1</version>
        <configuration>
          <release>17</release>
          <showWarnings>true</showWarnings>
          <compilerArgs><arg>-Xlint:all</arg><arg>-Werror</arg></compilerArgs>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>3.8.1</version>
        <executions>
          <execution>
            <id>unpack-coakka-native</id>
            <phase>process-resources</phase>
            <goals><goal>unpack</goal></goals>
            <configuration>
              <artifactItems>
                <artifactItem>
                  <groupId>io.github.phuong-tran.coakka</groupId>
                  <artifactId>coakka-http-runtime-jvm</artifactId>
                  <version>${coakka.version}</version>
                  <classifier>${coakka.target}</classifier>
                  <type>zip</type>
                  <outputDirectory>${project.build.directory}/coakka-native</outputDirectory>
                </artifactItem>
              </artifactItems>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>
Maven
mvn -q -Dcoakka.target=linux-aarch64 compile dependency:build-classpath -Dmdep.outputFile=target/classpath.txt
Java
java -Djava.library.path=target/coakka-native/native \
  -cp "target/classes:$(cat target/classpath.txt)" study.JavaUpload
Kotlin
java -Djava.library.path=target/coakka-native/native \
  -cp "target/classes:$(cat target/classpath.txt)" study.KotlinUploadKt
Gradle
build.gradle.kts
plugins {
    kotlin("jvm") version "2.3.10"
}

repositories {
    mavenCentral()
}

val coakkaTarget = providers.gradleProperty("coakkaTarget")
    .orElse("macos-aarch64")
val coakkaNative by configurations.creating

dependencies {
    implementation("io.github.phuong-tran.coakka:coakka-http-runtime-jvm:2.3.2")
    implementation("org.eclipse.angus:angus-mail:2.0.5")
    implementation("org.apache.commons:commons-fileupload2-core:2.0.0-M5")
    coakkaNative("io.github.phuong-tran.coakka:coakka-http-runtime-jvm:2.3.2:${coakkaTarget.get()}@zip")
}

val unpackCoakkaNative by tasks.registering(Sync::class) {
    from(coakkaNative.map(::zipTree))
    into(layout.buildDirectory.dir("coakka-native"))
}

kotlin {
    compilerOptions {
        jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
        freeCompilerArgs.add("-Xjdk-release=17")
        allWarningsAsErrors.set(true)
    }
}

java {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
}

tasks.withType<JavaCompile>().configureEach {
    options.release.set(17)
    options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror"))
}

tasks.register<JavaExec>("runJavaUpload") {
    dependsOn(unpackCoakkaNative)
    classpath = sourceSets["main"].runtimeClasspath
    mainClass.set("study.JavaUpload")
    standardInput = System.`in`
    jvmArgs("-Djava.library.path=${layout.buildDirectory.dir("coakka-native/native").get().asFile}")
}

tasks.register<JavaExec>("runKotlinUpload") {
    dependsOn(unpackCoakkaNative)
    classpath = sourceSets["main"].runtimeClasspath
    mainClass.set("study.KotlinUploadKt")
    standardInput = System.`in`
    jvmArgs("-Djava.library.path=${layout.buildDirectory.dir("coakka-native/native").get().asFile}")
}
settings.gradle.kts
rootProject.name = "coakka-http-multipart-stream-lab"
Java
gradle -PcoakkaTarget=linux-aarch64 runJavaUpload
Kotlin
gradle -PcoakkaTarget=linux-aarch64 runKotlinUpload

Gửi tệp 2 MiB

Dùng -F để curl tự tạo dấu phân cách của form. Ví dụ giới hạn tốc độ để có thể quan sát việc ghi tệp khi upload chưa xong.

Terminal
dd if=/dev/zero of=demo.bin bs=1024 count=2048
curl --silent --show-error --include --limit-rate 512k \
  -F '[email protected]' http://127.0.0.1:8080/upload/multipart-stream
cmp demo.bin uploads/streamed.bin

Kết quả đúng: 201 Created và saved streamed.bin (2097152 bytes). cmp không in gì nếu nội dung giống hệt.

Đọc giới hạn và kết quả

Để nhận tệp lớn hơn, tăng cả giới hạn tệp và giới hạn toàn bộ body. Đồng bộ cấu hình CoAkka HTTP Runtime và giới hạn của proxy nếu có. Bộ đệm đọc vẫn có thể giữ nhỏ.

SDK 2.3.0 cho phép cấu hình tối đa 8 MiB cho toàn bộ body, tính cả phần bao quanh form. Với tệp vượt mức này, hãy chia dữ liệu qua nhiều request và tải tiếp khi cần hoặc tải trực tiếp lên kho lưu trữ đối tượng.

Tệp
Tối đa 2 MiB (2.097.152 byte). Chỉ nhận 1 trường tệp tên file; tên gốc không được dùng làm đường dẫn.
Toàn bộ body
Tối đa 2 MiB + 16 KiB, tính cả header và dấu phân cách của form. Giới hạn này dành cho bài thực hành; khi triển khai, chọn thêm hạn mức đĩa, số lượt đồng thời và thời gian chờ.
Kết quả
413 khi vượt giới hạn; 400 khi form sai hoặc thiếu trường file. Tệp đã lưu từ request trước vẫn giữ nguyên.
Thử tệp lớn hơn 2 MiB
Terminal
head -c 2097153 /dev/zero > too-large.bin
curl --silent --show-error --include --limit-rate 512k \
  -F '[email protected]' http://127.0.0.1:8080/upload/multipart-stream

Thử ngắt giữa chừng

Chạy trong thư mục mới hoặc chuyển uploads/streamed.bin đã lưu sang chỗ khác. Script chỉ ngắt kết nối sau khi thấy dữ liệu trong tệp incoming-*. Nó thử ngắt giữa tệp và ngắt sau dấu kết thúc form nhưng trước khi HTTP nhận đủ body.

check_upload.py
check_upload.py
"""Verify multipart streaming, exact limits, and cleanup after disconnect."""

import http.client
import socket
import subprocess
import tempfile
import time
from pathlib import Path

PORT = 8080
ROUTE = "/upload/multipart-stream"
URL = f"http://127.0.0.1:{PORT}{ROUTE}"
UPLOADS = Path("uploads")
SAVED = UPLOADS / "streamed.bin"
FILE_LIMIT = 2 * 1024 * 1024
BODY_LIMIT = FILE_LIMIT + 16 * 1024
BOUNDARY = "portal-streaming-lab"
CONTENT_TYPE = f"multipart/form-data; boundary={BOUNDARY}"
PART = (
    f"--{BOUNDARY}\r\n"
    'Content-Disposition: form-data; name="file"; filename="../../demo.bin"\r\n'
    "Content-Type: application/octet-stream\r\n\r\n"
).encode("ascii")
END = f"\r\n--{BOUNDARY}--\r\n".encode("ascii")


def pending():
    return list(UPLOADS.glob("incoming-*"))


def wait_for(predicate, failure):
    deadline = time.monotonic() + 5
    while time.monotonic() < deadline:
        if predicate():
            return
        time.sleep(0.02)
    raise RuntimeError(failure)


def wrote_partial():
    for file in pending():
        try:
            if file.stat().st_size >= 8192:
                return True
        except FileNotFoundError:
            continue
    return False


def disconnect(payload, label):
    with socket.create_connection(("127.0.0.1", PORT), timeout=5) as connection:
        header = (
            f"POST {ROUTE} HTTP/1.1\r\n"
            f"Host: 127.0.0.1:{PORT}\r\n"
            f"Content-Type: {CONTENT_TYPE}\r\n"
            f"Content-Length: {len(payload) + 8192}\r\n\r\n"
        )
        connection.sendall(header.encode("ascii"))
        for offset in range(0, len(payload), 8192):
            connection.sendall(payload[offset:offset + 8192])
            time.sleep(0.01)
        wait_for(wrote_partial, "no bytes were written to the temporary file")
        assert not SAVED.exists(), "server published before HTTP end-of-body"
        # A real disconnect: close without sending the declared remaining bytes.
    wait_for(lambda: not pending(), "temporary file survived the disconnect")
    assert not SAVED.exists(), "disconnect published a file"
    print(f"{label}: saw temporary data, disconnected, then verified cleanup")


def post_small(payload, expected):
    client = http.client.HTTPConnection("127.0.0.1", PORT, timeout=10)
    try:
        client.request("POST", ROUTE, payload, {"Content-Type": CONTENT_TYPE})
        response = client.getresponse()
        response.read()
        assert response.status == expected, (response.status, expected)
    finally:
        client.close()


def curl_file(file, expected):
    output = subprocess.check_output([
        "curl", "--silent", "--show-error", "--max-time", "25", "--limit-rate", "512k",
        "--write-out", "\n%{http_code}", "-F", f"file=@{file};filename=../../demo.bin", URL,
    ], timeout=27)
    body, status = output.rsplit(b"\n", 1)
    assert int(status) == expected, output
    return body


def main():
    if not UPLOADS.is_dir() or pending() or SAVED.exists():
        raise SystemExit("Start the lab in a fresh directory before running this check.")
    fragment = bytes(range(256)) * 256
    disconnect(PART + fragment, "mid-file")
    disconnect(PART + fragment + END, "after form delimiter, before HTTP end")
    post_small(PART + b"missing closing delimiter", 400)
    post_small(PART + b"first\r\n" + PART + b"second" + END, 400)
    wait_for(lambda: not pending(), "invalid form left a temporary file")
    assert not SAVED.exists(), "invalid form published a file"

    with tempfile.TemporaryDirectory(prefix="coakka-upload-check-", dir=".") as directory:
        sample = Path(directory) / "demo.bin"
        data = fragment * (FILE_LIMIT // len(fragment))
        sample.write_bytes(data)
        assert curl_file(sample, 201) == b"saved streamed.bin (2097152 bytes)\n"
        assert SAVED.read_bytes() == data, "saved bytes differ from the upload"
        sample.write_bytes(data + b"x")
        curl_file(sample, 413)
        sample.write_bytes(data + b"x" * (BODY_LIMIT - FILE_LIMIT))
        curl_file(sample, 413)
        wait_for(lambda: not pending(), "oversized upload left a temporary file")
        assert SAVED.read_bytes() == data, "refused upload replaced the saved file"
    print("201 and exact 2 MiB; malformed forms 400; file and body limits 413")


if __name__ == "__main__":
    main()
Terminal
python3 check_upload.py

C/C++ dọn tệp khi nhận sự kiện hủy hoặc kết thúc sớm. Go, Java, Kotlin và Python dọn khi đọc bị lỗi. Node.js và Bun dọn khi nhận dispose. Client đã ngắt sẽ không nhận mã HTTP; dấu hiệu đúng là tệp tạm biến mất và không có tệp đích mới.