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.
@Override
 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 {
    response.setContentType("text/plain");
    response.getWriter().write(error(message));
    response.flushBuffer();
   } catch (IOException e) {
    log.error(null, e);
    errorModelAndView();
   }*/

   // 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.io.PrintWriter;
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) {
  super();
  this.body = body;
 }

 public PlainTextView() {
  super();
  this.body = null;
 }

 public String getContentType() {
  return CONTENT_TYPE;
 }

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

No comments:

Followers