Friday, September 26, 2008

Solution to Struts2 upload file error: the request was rejected because its size (XXX) exceeds the configured maximum (YYY)

The error message from the title is generated by Commons FileUpload and caught exception in class org.apache.struts2.dispatcher.multipart.MultiPartRequest is not translated to any custom message. It causes the problem with i18n because in polish or french application I would not appreciate english message. There are at least three solutions to this problem (all of them are pain in the ass): one is to reimplement org.apache.struts2.dispatcher.multipart.MultiPartRequest class; second one is to reimplement org.apache.struts2.interceptor.FileUploadInterceptor class. I found a third solution which is the least painful but as well ugly.

All you have to do is to implement validate() method in your Struts2 action class like this:
 
@Override
public void validate() {
Collection<?> tmp = getActionErrors();
Collection<String> errors = new ArrayList<String>();
for (Object o : tmp) {
if (o.toString().contains(
"the request was rejected because its size")) {

errors.add(getText("error.exceededUploadSize"));
} else {
errors.add(o.toString());
}
}

setActionErrors(errors);
}


Enjoy!

5 comments:

Anonymous said...

Yes, I got the same issue. Text of that message is hardcoded into FileUpload library:

+ if (sizeMax >= 0 && requestSize > sizeMax) {
+ throw new SizeLimitExceededException(
+ "the request was rejected because its size (" + requestSize
+ + ") exceeds the configured maximum (" + sizeMax + ")",
+ requestSize, sizeMax);
+ }

And I am going to apply the fix like in this post. Does anybody know more ellegant way?

Anonymous said...

A little more reliable check should look like this:

public static Pattern REJECTED_FILE_SIZE_PATTERN = Pattern.compile(".*reject.*size.*");
...
if (REJECTED_FILE_SIZE_PATTERN.matcher(s).matches()) {
//
} else {
//
}

Przemyslaw Bielicki said...

Thanks a lot for your comments Anonymous :)

I have to disagree with your solution as it is a huge mistake. On my machine matcher(s).matches() is 100 times (!!!) slower than contains() method.

Don't overengineer your code - keep it simple.

And thanks again for your comments.

Pequeño said...

What brilliant solution!

Many thanks ;)

Anonymous said...

Thank you very much, I wated one day for such a silly fix. your solution works very well.

Excellent fix.