If the file size exceeds the limit specified in @MultipartConfig(maxFileSize) , an exception will be thrown when accessing the HttpServletRequest.getParts() method.
For example, when deploying a servlet running on Wildfly 10 application server, an exception looks like this:
java.lang.RuntimeException: java.io.IOException: UT000054: The maximum size 10485760 for an individual file in a multipart request was exceeded ... Caused by: java.io.IOException: UT000054: The maximum size 10485760 for an individual file in a multipart request was exceeded
If your task is simply to prevent the download of large files, then additionally do not have to do anything, because the process will be aborted on line
Part part = request.getPart("photo")
and will not reach to save to the database. If additional processing is required when retrieving large files, getPart should be getPart in try/catch
UPDATE
When you deploy an application running Tomcat 7, the thrown exception looks like this:
java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field binaryFile exceeds its maximum permitted size of 2097152 bytes. ... Caused by: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field binaryFile exceeds its maximum permitted size of 2097152 bytes.
Here is the simplest example of code that catches an exception and redirects the user to the error page:
@WebServlet("/file") @MultipartConfig( fileSizeThreshold = 1024 * 1024 * 2, maxFileSize = 1024 * 1024 * 2, maxRequestSize = 1024 * 1024 * 2) public class FilesServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { for (Part part : req.getParts()) { //работа с полученными файлами } } catch (Exception e) { e.printStackTrace(); if (e.getCause() != null && e.getCause() instanceof FileUploadBase.FileSizeLimitExceededException) { resp.sendRedirect(getServletContext().getContextPath() + "/fileSizeError.html"); } } } }