File Upload functionality in Struts 2

In order to add file upload functionality we will add an action class FileUploadAction to our webproject. Create file, which should look like:

In above class file we have declared few attributes:

  • private File userImage -> This will store actual uploaded File
  • private String userImageContentType -> This string will contain the Content Type of uploaded file (like if user has uploaded an image file then the content type will be jpg/gif/png depending on the file type).
  • private String userImageFileName -> This string will contain the file name of uploaded file.

Create appropriate getter and setter methods for all the attributes. The fields userImageContentType and userImageFileName are optional. This is just to get some extra information of uploaded file. Also, you need to follow the naming standard if you providing the content type and file name string. The name should be ContentType and FileName. For example if the file attribute in action file is private File uploadedFile, the content type will be uploadedFileContentType and file name uploadedFileFileName these naming conventions are mandatory.

Also note in above action class, we have implemented interface org.apache.struts2.interceptor.ServletRequestAware. This is to get servletRequest object. We have used FileUtil.copyFile() method of commons-io package to copy the uploaded file in root folder. Actually it creates one mirror copy of that file and stores it onto the server. If user wants to find appropriate file then using file path, he/she will be able to access the same file from the server.

Now, create two JSP files in WebContent folder. UserImage.jsp will display a form to user to upload image. In the form tag you have to add one extra attribute that is enctype=”multipart/form-data” that indicates how the form-data should be encoded when submitting on to the server. It is especially used when user wants to upload some data on the server. On submit, the file will be uploaded and saved on server. User will be sent to SuccessUserImage.jsp file where File details will be displayed. UserImage.jsp would look something like:

Note that in XML file given below we have specified two parameters to fileUpload interceptor, maximumSize and allowedTypes. These are optional parameters that we can specify to interceptor. The maximumSize param will set the maximum file size that can be uploaded. By default this is 2MB. And the allowedTypes param specify the allowed content types of file which can be uploaded. Here we have specified it to be an image file (image/png,image/gif,image/jpeg,image/pjpeg). So the struts.xml should look like:

The SuccessUserImage.jsp would look like:

Kindly put on your queries as comment to this post.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.