trainingtrains Logo

91-9990449935

 0120-4256464

Struts2 File Upload Example

The fileUpload interceptor automatically works for all the requests that includes files.

We can use this interceptor to control the working of file upload in struts2 such as defining allowed types, maximum file size etc.

Parameters of fileupload interceptor

There are 2 parameters defined for fileupload interceptor.

ParameterDescription
maximumSizespecifies maximum size of the file to be uploaded.
allowedTypes specifies allowed types. It may be image/png, image/jpg etc.

It automatically adds 3 parameters in the request:

  1. File file represents the file. We can apply methods on this object.
  2. String fileName represents the filename of the file.
  3. String contentType specifies the content type of the file.

Image upload example using struts 2

Let's see the directory structure of file upload application.

file upload in struts 2 directory structure

1) Create UserImage.jsp

This jsp page creates a form using struts UI tags. It receives name, password and email id from the user.

index.jsp

2) Create SuccessUserImage.jsp

This jsp page creates a form using struts UI tags. It receives name, password and email id from the user.

SuccessUserImage.jsp

3) Create the action class

This action class inherits the ActionSupport class and overrides the execute method.

RegisterAction.java

4) Create struts.xml

This xml file defines an extra result by the name input, and an interceptor jsonValidatorWorkflowStack.

struts.xml


Output

struts file upload example 1 struts 2 file upload example 2

Image will not be displayed in the current project. Visit the image location printed in the server console to see the image.