How to upload two different files and validate their type and size in Struts2?

146 views Asked by At

I have a form on jsp and it has two file inputs, one to upload profile picture and one to upload PDF file.

I want to validate that

  • image input should accept only .jpeg or .png and its size should not exceed 200KB.
  • PDF input should be only PDF and size should not be more than 2MB.

How can I put different validations for different files in the same form ?

1

There are 1 answers

2
Andrea Ligios On

File limitations are request-related. If you need two different settings to be applied, you'd need two different requests (hence two forms), that is obviously not the wanted solution.

Then you can easily overcome this by applying:

  • in struts.xml the file type (image types, pdf)
  • in struts.xml the 2MB limit (the higher of the two)
  • in action validate(), or in XML validation, or in annotation validation, a control like
    "if file is of type image and size > 200KB, raise an error".

EDIT:

By the way i did it by writing my own interceptor.

Of course, if you have to apply this logic to many actions, then a custom Interceptor helps you DRY.

Just ensure you've understood how validation works, and add field errors from within your Interceptor in case it fails, so that the INPUT result will be automatically returned by the Worflow Interceptor.