Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 119 ยท Spring Framework

Spring MVC: File Upload and Pagination

Handle file uploads with MultipartFile and paginate long lists with Page and PageRequest in Spring MVC, with the same ideas in plain servlets and runnable plain-Java models.

Two features show up in almost every list-and-form application: letting users upload files (a profile photo, a CSV import, an invoice PDF) and splitting long lists into pages. Both look simple in a tutorial and go wrong in production: uploads without size limits fill the disk, trusted file names let attackers write outside the upload folder, and pages without a stable sort order show the same row twice.

In this lesson you will handle uploads with MultipartFile, set size limits, and store files safely, then build a paged list controller with page links. Both topics also get a plain-servlet version, because the underlying mechanism is the same. Spring MVC and a servlet container can't run on this page, so the real code is shown read-only, and each topic has a runnable program that reproduces the behavior in plain Java (an HTTP server and a client for uploads, H2 for paging). You should know Spring MVC and, for the second half, Spring Data JPA.

How a file upload travels

An HTML form with enctype="multipart/form-data" sends the request body as several parts separated by a boundary string. Each part has its own headers: a normal field has a name, a file part also has a filename and a Content-Type.

HTML
<form method="post" action="/upload" enctype="multipart/form-data">
  <input type="text" name="description">
  <input type="file" name="file" accept=".txt,.png,.csv">
  <button>Upload</button>
</form>

Without that enctype, the browser sends only the file's name. This is one of the most common upload bugs. The servlet container parses the multipart body, and Spring wraps each file part in a MultipartFile.

Receiving a file in a controller

Java
@Controller
public class UploadController {

    private static final Set<String> ALLOWED = Set.of("txt", "png", "csv");
    private final Path uploadDir;

    public UploadController(@Value("${app.upload-dir}") String uploadDir) {
        this.uploadDir = Path.of(uploadDir);
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file,
                         @RequestParam String description,
                         RedirectAttributes redirect) throws IOException {

        if (file.isEmpty()) {                                   // no file chosen, or a zero-byte file
            redirect.addFlashAttribute("error", "Please choose a file");
            return "redirect:/upload";
        }
        String clean = StringUtils.cleanPath(file.getOriginalFilename());      // for display only
        String extension = StringUtils.getFilenameExtension(clean);
        if (extension == null || !ALLOWED.contains(extension.toLowerCase())) {
            redirect.addFlashAttribute("error", "Only " + ALLOWED + " files are accepted");
            return "redirect:/upload";
        }

        String storedName = UUID.randomUUID() + "." + extension.toLowerCase();  // our own name
        file.transferTo(uploadDir.resolve(storedName));                         // writes the file

        redirect.addFlashAttribute("message", "Stored " + clean);
        return "redirect:/upload";                                              // Post/Redirect/Get
    }
}

Useful MultipartFile methods: getOriginalFilename(), getContentType(), getSize(), isEmpty(), getBytes(), getInputStream() and transferTo(Path). Use @RequestParam List<MultipartFile> files with <input type="file" multiple> for several files at once.

Limits and configuration

Always set limits. With Spring Boot, two properties do it:

PROPERTIES
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=10MB

Without Boot, the servlet registration carries the limits, and you declare a MultipartResolver bean named multipartResolver. Spring 6 removed the old Commons FileUpload resolver, so the servlet container's own parser is the only option now:

Java
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    // ... root/servlet configuration as in the previous lesson ...

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        registration.setMultipartConfig(new MultipartConfigElement(
            System.getProperty("java.io.tmpdir"), 5 * 1024 * 1024, 10 * 1024 * 1024, 0));   // location, file max, request max, threshold
    }
}

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }
}

When a file exceeds the limit, Spring raises a MaxUploadSizeExceededException. Catch it in a @ControllerAdvice and turn it into a friendly message or a 413 Payload Too Large response, otherwise users see the generic error page.

Storing files safely

Treat everything about the upload as hostile, including the file name, the declared content type and the size:

  • Never use the client's file name as the path. A name like ../../etc/cron.d/job or C:\Windows\x.dll tries to escape the folder. Generate your own name (a UUID) and keep the original only as a label for display, after cleaning it.
  • Allow-list the extension (and for important cases check the file's first bytes, because the content type header is also supplied by the client).
  • Store uploads outside the web root and serve them through a controller that checks permissions, so an uploaded .html or .jsp can never run as part of your site.
  • Limit the size at the container (above) and again in code if different forms have different limits.

The program below is not Spring. It starts a small HTTP server, sends real multipart/form-data requests to it with HttpClient, parses the parts with a few lines of code (this is what the container does for you), and applies the same checks as the controller above. Look at what each file name turned into.

Java A multipart upload endpoint with safe file names, limits and an allow-list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The traversal attempt ../../etc/passwd.txt was reduced to passwd.txt, and the Windows path to photo.PNG, but more importantly neither name decided where the bytes went: everything was written as upload-N.ext. The .exe was refused, the empty file got a clear message, and the oversized body was rejected before any parsing. Real containers behave the same way, with the parsing done in the servlet container and Spring seeing only the finished MultipartFile objects.

The same upload with plain servlets

Servlet 3.0 added multipart support to the API itself. You mark the servlet with @MultipartConfig and read the part:

Java
@WebServlet("/upload")
@MultipartConfig(maxFileSize = 5 * 1024 * 1024, maxRequestSize = 10 * 1024 * 1024)
public class UploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Part file = request.getPart("file");                          // the file part
        String description = request.getParameter("description");     // normal fields still work

        if (file == null || file.getSize() == 0) {
            response.sendError(400, "Please choose a file");
            return;
        }
        String clean = Path.of(file.getSubmittedFileName()).getFileName().toString();   // display name only
        String stored = UUID.randomUUID() + ".txt";                    // check the extension first in real code
        try (InputStream in = file.getInputStream()) {
            Files.copy(in, Path.of(getServletContext().getInitParameter("uploadDir"), stored));
        }
        response.sendRedirect(request.getContextPath() + "/upload?stored=" + URLEncoder.encode(clean, UTF_8));
    }
}

Spring's MultipartFile is a thin wrapper around this Part. The rules for naming and limits are identical.

Pagination: never load the whole table

A page of results needs two pieces of information: the rows of the current page and the total count (so that the page links can be drawn). In SQL that is a COUNT(*) query and a query with LIMIT and OFFSET. With Spring Data JPA, a Pageable parameter and a Page return value do both:

Java
@Controller
@RequestMapping("/books")
public class BookController {

    private final BookRepository books;

    public BookController(BookRepository books) { this.books = books; }

    @GetMapping
    public String list(@RequestParam(defaultValue = "") String q,
                       @RequestParam(defaultValue = "0") int page,           // 0-based, like Spring Data
                       @RequestParam(defaultValue = "10") int size,
                       Model model) {
        size = Math.min(Math.max(size, 1), 100);                              // never trust the client's page size
        Pageable pageable = PageRequest.of(Math.max(page, 0), size, Sort.by("title", "id"));   // id = tie-breaker
        Page<Book> result = books.findByTitleContainingIgnoreCase(q, pageable);

        if (result.getTotalPages() > 0 && page >= result.getTotalPages()) {
            return "redirect:/books?q=" + UriUtils.encode(q, UTF_8) + "&page=" + (result.getTotalPages() - 1);
        }
        model.addAttribute("page", result);
        model.addAttribute("q", q);
        return "books/list";
    }
}

public interface BookRepository extends JpaRepository<Book, Long> {
    Page<Book> findByTitleContainingIgnoreCase(String title, Pageable pageable);
}

Spring can also build the Pageable for you from ?page=&size=&sort= if you declare it as a method parameter, optionally with @PageableDefault(size = 10, sort = "title"). The Page object offers getContent(), getNumber(), getTotalPages(), getTotalElements(), hasNext() and hasPrevious(). Using it from a Thymeleaf template, the page links (the page number in the URL is 0-based, the one shown to people is 1-based):

HTML
<table>
  <tr th:each="book : ${page.content}"><td th:text="${book.title}">Title</td></tr>
</table>

<nav th:if="${page.totalPages > 1}">
  <a th:if="${page.hasPrevious()}" th:href="@{/books(q=${q}, page=${page.number - 1})}">Previous</a>
  <span th:each="i : ${#numbers.sequence(0, page.totalPages - 1)}">
    <strong th:if="${i == page.number}" th:text="${i + 1}">1</strong>
    <a th:unless="${i == page.number}" th:href="@{/books(q=${q}, page=${i})}" th:text="${i + 1}">2</a>
  </span>
  <a th:if="${page.hasNext()}" th:href="@{/books(q=${q}, page=${page.number + 1})}">Next</a>
</nav>

That draws every page number, which is fine for 5 pages and unusable for 500. Real sites show the first and last page and a small window around the current one, with an ellipsis in between. The model below does all of it against a real database (H2): a count query, a LIMIT/OFFSET query with a tie-breaker in the sort, the link bar, a search filter that keeps its place in the links, and a request for a page past the end.

Java Paged queries with LIMIT/OFFSET, a count and a page link bar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check three things in the output. The last page has only 7 of the 10 rows, and the count query made totalPages exactly 5. The search results carry q=Java in every link, so clicking Next keeps the filter. And a page number past the end returns zero rows, which a controller should turn into a redirect to the last page (or a 404) instead of showing an empty table.

Always sort a paged query, and add a unique column as the last sort key. Without an ORDER BY, the database may return rows in any order, so page 2 can repeat or skip rows of page 1. If you sort by a column with duplicates (title, date), add id as a tie-breaker. Also remember that OFFSET 100000 still makes the database walk past 100,000 rows. For very large tables, use keyset pagination (WHERE id > :lastSeenId ORDER BY id LIMIT 10), as described in Spring Data JPA.

Pagination in plain servlets

Without Spring Data, you write the same two queries yourself and pass the numbers to the JSP:

Java
int page = parseOrDefault(request.getParameter("page"), 0);
int size = 10;
int total = dao.count();                                   // SELECT COUNT(*) FROM book
int totalPages = (int) Math.ceil(total / (double) size);
List<Book> books = dao.findPage(page * size, size);        // ... ORDER BY title, id LIMIT ? OFFSET ?

request.setAttribute("books", books);
request.setAttribute("page", page);
request.setAttribute("totalPages", totalPages);
request.getRequestDispatcher("/WEB-INF/views/books.jsp").forward(request, response);

In JSP, a <c:forEach begin="0" end="${totalPages - 1}" var="i"> loop draws the links, as shown in JSTL and Expression Language. On databases without LIMIT/OFFSET, the standard form is OFFSET ? ROWS FETCH NEXT ? ROWS ONLY. The logic is identical to what Page hides.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A file upload form posts, but the controller receives only the file's name as text, not its content. What is the most likely cause?

    Without multipart encoding, browsers send only the file name in a normal URL-encoded field. The parts, and the file content, need multipart/form-data.
  2. 2. Why should the controller NOT use file.getOriginalFilename() directly as the name of the file on disk?

    The original file name is user input. Generate your own stored name and keep the original only as a cleaned display label.
  3. 3. In a Spring Data paged query, what does Page<T> carry besides the rows of the current page?

    A Page runs a count query as well, so the view can draw the page links. A Slice skips the count and only knows whether a next page exists.
  4. 4. Why add id as a second sort key in Sort.by("title", "id")?

    With duplicate sort values the database may order the ties differently from one query to the next. A unique tie-breaker makes the pages stable.
  5. 5. A user requests ?page=99 but the result has only 5 pages. What is a sensible controller behavior?

    A page past the end returns no rows. Redirecting to the last page (or a 404) is friendlier than an empty table with working-looking links.

Summary

  • File uploads need enctype="multipart/form-data". Spring gives each file part to the controller as a MultipartFile; plain servlets use @MultipartConfig and Part.
  • Set size limits (spring.servlet.multipart.* or MultipartConfigElement), handle MaxUploadSizeExceededException, and answer with a clear message.
  • Store uploads under names you generate, in a folder outside the web root, after checking the extension; keep the original file name only as a cleaned label.
  • Pagination needs the rows of one page plus a total count. Spring Data's PageRequest and Page do both; plain JDBC uses COUNT(*) and LIMIT/OFFSET.
  • Page numbers are 0-based in Spring Data and in the URL, 1-based for people. Clamp the page size, keep filters in every link, and redirect when the page is past the end.
  • Always give a paged query a stable sort with a unique tie-breaker; use keyset pagination for very deep pages.

Next: Spring Events and Transactions covers how Spring coordinates work such as saving the upload record and notifying other components in one transaction.