Javalin File Upload: Simple Examples for Beginners

One common task is handling file uploads—let’s explore how to implement this in Javalin with easy-to-follow examples.

Example 1: Basic File Upload with Javalin

This example uses Javalin’s built-in upload handler to save files to a local directory.

Step 1: Add Dependencies

<!-- Maven pom.xml -->
<dependencies>
    <dependency>
        <groupId>io.javalin</groupId>
        <artifactId>javalin</artifactId>
        <version>6.0.0</version>
    </dependency>
</dependencies>

Step 2: Create the Upload Endpoint

import io.javalin.Javalin;
import io.javalin.http.UploadedFile;

public class FileUploadExample {
    public static void main(String[] args) {
        Javalin app = Javalin.create().start(7070);

        app.post("/upload", ctx -> {
            UploadedFile file = ctx.uploadedFile("file"); // "file" matches HTML input name
            if (file != null) {
                String savePath = "/tmp/uploads/" + file.getFilename();
                file.saveTo(savePath); // Save to disk
                ctx.result("File uploaded: " + file.getFilename());
            } else {
                ctx.status(400).result("No file received");
            }
        });

        System.out.println("Server running at http://localhost:7070");
    }
}

Step 3: Create an HTML Form

<!-- upload.html -->
<!DOCTYPE html>
<html>
<body>
    <form action="http://localhost:7070/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" />
        <button type="submit">Upload</button>
    </form>
</body>
</html>

Output

  1. Start the server and open upload.html in a browser.
  2. Select a file and click Upload.
  3. The server responds with:
    File uploaded: example.txt
  4. Check /tmp/uploads/ on your server—the file will be there!

Example 2: Advanced Upload with File Validation

Let’s add size limits and file type checks using Apache Commons FileUpload (for more control).

Step 1: Add Dependencies

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.5</version>
</dependency>

Step 2: Create the Endpoint

import io.javalin.Javalin;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.MultipartConfigElement;
import java.io.File;
import java.util.List;

public class AdvancedFileUpload {
    public static void main(String[] args) {
        Javalin app = Javalin.create(config -> {
            config.register(MultipartConfigElement::new); // Enable multipart support
        }).start(7070);

        app.post("/advanced-upload", ctx -> {
            // Check if request is multipart
            if (!ServletFileUpload.isMultipartContent(ctx.req())) {
                ctx.status(400).result("Not a multipart request");
                return;
            }

            // Configure upload settings
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(1024 * 1024); // 1MB limit

            try {
                List<FileItem> items = upload.parseRequest(ctx.req());
                for (FileItem item : items) {
                    if (!item.isFormField()) { // Skip form fields, process files only
                        String fileName = item.getName();
                        String fileType = fileName.substring(fileName.lastIndexOf("."));

                        // Validate file type
                        if (!fileType.matches(".(jpg|png|txt)")) {
                            ctx.status(400).result("Invalid file type: " + fileType);
                            return;
                        }

                        // Save file
                        String savePath = "/tmp/uploads/" + fileName;
                        item.write(new File(savePath));
                        ctx.result("Uploaded: " + fileName);
                    }
                }
            } catch (Exception e) {
                ctx.status(500).result("Upload failed: " + e.getMessage());
            }
        });
    }
}

Output

  1. Upload a file larger than 1MB or an unsupported type (e.g., .exe).
  2. The server responds with:
    Invalid file type: .exe
    or
    Upload failed: File size limit exceeded

Key Takeaways

  • Javalin’s UploadedFile is the simplest way to handle uploads.
  • For advanced needs (e.g., size limits, type checks), use Apache Commons FileUpload.
  • Always validate files before saving them to disk!

Happy coding! 🚀

Javalin File Upload Java Web Development Lightweight Framework Apache Commons FileUpload