File Uploads

Handling file uploads is very simple, and several options for handling files are available. For example, you can access the uploaded file as an in memory byte array or as a string for text uploads, or you can save the file to disk, or access the input stream of the upload.

Given an HTML form like this:

<h1>Upload demo</h1>

<form action="/upload" method="post" enctype="multipart/form-data">
    <label>Select a file
        <input type="file" name="your-file" required>
    <input type="submit" value="Upload">
(see full file)

You can access the your-file upload by looking it up on the request object:

public class UploadExample {
    public static void main(String[] args) {
        MuServer server = httpServer()
            .withMaxRequestSize(1_000_000_000 /* 1GB */)
            .addHandler(Method.POST, "/upload", (request, response, pathParams) -> {

                UploadedFile file = request.uploadedFile("your-file");
                File dest = new File("target/upload-demo/" + file.filename());
                response.write(file.filename() + " (" + file.size() + " bytes) of type " +
                    file.contentType() + " saved to " + Mutils.fullPath(dest));

            .addHandler(ResourceHandlerBuilder.fileOrClasspath("src/main/resources/samples", "/samples"))
        System.out.println("Upload example started at " + server.uri().resolve("/upload.html"));
(see full file)

Multiple file uploads are also supported. See the UploadedFile docs for more info.