Oops Null Pointer

Java programming related

Struts2 file upload max size error

A few lessons I learned from getting the Struts2 file upload feature to handle files larger that 2MB:

1. There are two settings that have to be changed to handle more than 2MB.

The first is the fileUpload interceptor’s maximumSize param and the second is the struts.multipart.maxSize. I set both in the example below in the struts.xml file (the struts.multipart.maxSize can also be set in the struts.properties or web.xml).

<!-- 104857600 - 100MB -->
<constant name="struts.multipart.maxSize" value="104857600" />
<action name="importCSVFile" method="importCSVFile" class="ImportCSVDataAction" >
  <result name="success" type="tiles">importdata</result>
  <result name="error" type="tiles">importdata</result>
  <result name="input" type="tiles">importdata</result>
  <interceptor-ref name="paramsPrepareParamsStack">
    <!-- 52428800 = 50mb -->
    <param name="fileUpload.maximumSize">52428800</param>

Notice that the above code overrides the fileUpload interceptor that is in the paramsPreparParams stack. It’s a nice shorthand way of using the interceptor name as the prefix and the param name as the suffix.

2. When either of the max size limits are exceeded you get a different error message.

  • The struts.multipart.maxSize gives a fairly clear and readable message as an action error
  • The maximumSize param gives a very ugly message as a field error
I think both are not nice enough to present to the user so I catch them both in the validate method and replace with a nicer message:
private static final String MAX_FILE_SIZE = "50MB";
public void validate()
  List<String> uploadErrors = (List<String>)getActionErrors();
  if (getFieldErrors().get("upload") != null)
  for (String err : uploadErrors)
    if (err.startsWith("File too large") || err.startsWith("the request was rejected because its size"))
      addActionError(getText(MSG_KEY_ERROR_FILE_TOO_LARGE, Arrays.asList(MAX_FILE_SIZE)));

3. Note that in the first example of the struts.xml code I have the input result set. The max size errors will return a input result, so if you don’t have this defined you get a servlet error message.

One response to “Struts2 file upload max size error

  1. B.E. April 11, 2013 at 3:01 pm

    Great tip and nice work getting the settings into one file!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: