Javatpoint Logo
Javatpoint Logo

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.

Automatically added parameters

It automatically adds 2 parameters in the request:

  1. String fileName represents the filename of the file.
  2. String contentType specifies the content type of the file.

The fileName and contentType name depends on the request parameter for the file. If filename is file, you need to use fileFileName and fileContentType. If filename is userImage, you need to use userImageFileName and userImageContentType in the Action class.


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 file 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.





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA