Friday, February 01, 2013

SwfUpload plugin and Spring MaxUploadSizeExceededException

IN order to show the user an error message the SwfUpload plugin needs a plain text response from the server using the keyword "ERROR:" like in "ERROR: Maximum upload size exceeded" however when Spring throws the below exception the request does not get even to the controller:
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size of 1000000 bytes exceeded; nested exception is org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (2097682) exceeds the configured maximum (1000000)
In order to resolve this issue you need to implement HandlerExceptionResolver in your controller which basically means you need to add a method to it.
 public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object,
   Exception exception) {
  if (exception instanceof MaxUploadSizeExceededException) {
   String message = exception.getMessage();
   // The below will still render the default exception handler view
   /*try {
   } catch (IOException e) {
    log.error(null, e);

   // Returning a Plain Text View
   return new ModelAndView(new PlainTextView(error(message.substring(0, message.indexOf(";")))));

  } else {
   return errorModelAndView();

 private ModelAndView errorModelAndView() {
  return new ModelAndView("/error?id=error.internal");
Note the commented lines. Unfortunately it is not as easy as just write to the response. Spring expects a valid ModelAndView object as response. That is the reason why I had to create a special PlainTextView:
package com.nestorurquiza.utils.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.View;

public class PlainTextView implements View {
 private static final String CONTENT_TYPE = "plain/text";
 public static final String BODY = "body";
 private String body;

 public PlainTextView(String body) {
  this.body = body;

 public PlainTextView() {
  this.body = null;

 public String getContentType() {
  return CONTENT_TYPE;

 public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
  PrintWriter out = response.getWriter();

No comments: