日本語

Uploads

An upload is an action that also receives the files picked in a file input. Its handler reads them into memory, or one chunk at a time for large files.

Uploads

An Upload<S, A> is an action that also receives the files picked in a FileInput<S>. Declare it on an upload line of routes! with its handler, put FileInput::input on the page, and pass the same constant to call or call_with.

use axum::Router;
use axum::http::StatusCode;
use hypersig::html::{button, div, attr};
use hypersig::{FileInput, FileName, Page, Patches, Signals, Upload, Uploaded};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Profile {
    picture: String,
    uploading: bool,
    problem: String,
}

// Both constants carry the page's type, so a file input from another page does not compile.
const PICTURE: FileInput<Profile> = FileInput::new("picture");

hypersig::routes! {
    fn pages(Router<()>);
    upload AVATAR: Upload<Profile> = "/avatar" max_bytes 256 * 1024 => avatar;
}

let signals = Profile { picture: String::new(), uploading: false, problem: String::new() };
let page = Page::new("Profile", signals).child(
    div()
        .child(PICTURE.input().attr(attr::ACCEPT, "image/png"))
        .child(
            button()
                .on_click(
                    AVATAR
                        .call(PICTURE)
                        .indicator(Profile::uploading())
                        .error(Profile::problem())
                        .then(PICTURE.clear()),
                )
                .text("Upload"),
        ),
);

// The handler gets the arguments and the files, and answers as an action's does.
async fn avatar((): (), uploaded: Uploaded<()>) -> Result<Patches<Profile>, StatusCode> {
    let [file] = uploaded.files() else {
        return Err(StatusCode::UNPROCESSABLE_ENTITY);
    };
    if !file.bytes().starts_with(b"\x89PNG") {
        return Err(StatusCode::UNPROCESSABLE_ENTITY);
    }
    let name = file.file_name().and_then(FileName::base_name).unwrap_or("picture").to_owned();
    Ok(Profile::picture().patch(name).into())
}

let _app: Router = pages(Router::new());
ItemWhat it is
const fn FileInput::new(name: &'static str) -> FileInput<S>A file input named name. An empty name in a const is a compile error
FileInput::input(self) -> El<S>The <input type="file">. Add multiple or accept to it as to any element
FileInput::clear(self) -> Stmt<S>Empties the input, such as after its files were sent
Upload::call(&self, files: FileInput<S>) -> Call<S>A call that sends the files. It exists only on Upload<S, ()>
Upload::call_with(&self, files: FileInput<S>, args: impl IntoExpr<S, A>) -> Call<S>A call that sends the files and args, evaluated in the browser when the call runs

The call is a Call<S> like an action's, so indicator, error, and then work as they do there. PICTURE.input() is an <input type="file">, and the page above adds accept="image/png" to it.

Both constants carry the page's type S, so a file input of another page does not compile:

use hypersig::{FileInput, Patches, Signals, Upload, Uploaded};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Profile {}

#[derive(Signals, Serialize, Deserialize)]
struct Gallery {}

const PHOTO: FileInput<Gallery> = FileInput::new("photo");

hypersig::routes! {
    fn pages(Router<()>);
    upload AVATAR: Upload<Profile> = "/avatar" => avatar;
}

// error[E0308]: mismatched types
// expected `FileInput<Profile>`, found `FileInput<Gallery>`
let _upload = AVATAR.call(PHOTO);

What an upload sends

An upload is a POST with a multipart/form-data body. Its first part holds the arguments, and each file picked in the input follows in the order the visitor picked them. An input with no file picked sends no file. A form on another site can send a multipart/form-data body too, so the runtime adds a header to an upload that such a form cannot set, and the router refuses a request without it.

The handler

The handler receives an Uploaded<A> with the arguments and each file's name, media type, and bytes. It answers as an action's handler does, so it can return a Result and take an extractor.

MethodReturns
Uploaded::args&A, the arguments the call passed
Uploaded::files&[UploadedFile], in the order the visitor picked them
Uploaded::into_parts(A, Vec<UploadedFile>), to own both
UploadedFile::file_nameOption<FileName<'_>>, the name on the visitor's computer
UploadedFile::content_typeOption<&str>, the media type the browser sent, such as image/png
UploadedFile::bytes, into_bytes&[u8] or Vec<u8>, the file's contents

A visitor can send any text as the name, such as ../../etc/passwd, so it reaches the handler as a FileName, not as a &str that a path could be joined with by accident. FileName::base_name is the part after the last / or \, or None where that is empty, ., .., or holds a control character, and FileName::as_sent is the text as sent. Store a file under a name the application chooses, and use the base name for showing it or reading its extension.

The file name and the media type come from the visitor's browser, so check the bytes before trusting them. The auth example accepts a picture only when its first bytes are those of a PNG or a JPEG.

The size limit

A body longer than Upload::DEFAULT_MAX_BYTES (8 MiB), or the limit that max_bytes after the path sets, gets a 413, before it is read when its Content-Length says so. The limit counts the whole body, the arguments and the multipart framing included, and Upload::limit returns it.

Large files

An upload line reads every file into memory before its handler runs, so keep its limit near the largest file you accept. For larger files, write stream before the path. Its handler receives an UploadStream<A>: the arguments, already read because the runtime sends them first, and next_file, which yields each file for the handler to read with chunk as its bytes arrive.

use axum::Router;
use hypersig::{Patches, RequestError, Signals, Upload, UploadStream};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Library {
    received: u64,
}

hypersig::routes! {
    fn pages(Router<()>);
    upload VIDEO: Upload<Library> = stream "/video" max_bytes 512 * 1024 * 1024 => receive;
}

// Each file arrives in chunks, and none is kept in memory unless the handler keeps it.
async fn receive((): (), mut upload: UploadStream<()>) -> Result<Patches<Library>, RequestError> {
    let mut received = 0;
    while let Some(mut file) = upload.next_file().await? {
        while let Some(chunk) = file.chunk().await? {
            // Write `chunk` to a file or a bucket here.
            received += chunk.len() as u64;
        }
    }
    Ok(Library::received().patch(received).into())
}

let _app: Router = pages(Router::new());

Once the body passes the limit, next_file or chunk returns a RequestError with status 413, which the handler can return with ?. next_file skips the part of the previous file that was not read. The file that next_file returns borrows the stream, so the next file cannot be asked for while the handler holds it.

Requests an upload refuses

Both kinds of line refuse these requests with a RequestError, and skip parts other than the arguments and the files:

StatusRequest
403 ForbiddenA Sec-Fetch-Site other than same-origin, or no header of an upload from the page
415 Unsupported Media TypeA body that is not multipart/form-data
413 Payload Too LargeA body longer than the limit
400 Bad RequestA malformed body, a first part that is not the arguments, or arguments that do not deserialize into A

A handler's extractor runs before the body is read, so an upload from a visitor who is not signed in is refused before its files arrive.

What the compiler does not check

The compiler does not check that the input is on the page. When the call finds no input of its name, the browser's console shows hypersig: no file input named "picture" and the upload goes out without files. Inside a list item, the browser looks for the input in the same item first.

Two file inputs with one name, where one lookup can reach both, make Page::render panic before the page is served. Each item of a list may carry the same name. File inputs and node refs are looked up apart, so a file input and a node ref never share a name.

Next, Storing data keeps what a handler receives, and Security lists what the router refuses and why.