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>
    </label>
    <input type="submit" value="Upload">
</form>
(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());
                file.saveTo(dest);
                response.write(file.filename() + " (" + file.size() + " bytes) of type " +
                    file.contentType() + " saved to " + Mutils.fullPath(dest));

            })
            .addHandler(ResourceHandlerBuilder.fileOrClasspath("src/main/resources/samples", "/samples"))
            .start();
        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.