Struts2

Struts 2 File Upload Example

In this example you will learn how to do file upload with the help of the built-in FileUploadInterceptor. To do this first we need to get the file form the user. We use the Struts 2 tags to build our form. The encoding type of the form should be set to multipart/form-data and the HTTP method should be set to post. The index.jsp page contains the following code.

Create two JSP file in WebRoot folder. index.jsp will display a form to user to upload image. On submit, the file will be uploaded and saved on server. User will be sent to success.jsp file where File details will be displayed. Copy following code into it.

index.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Upload User Image</title>
</head>
 
<body>
<h2>Struts2 File Upload & Save Example</h2>
<s:actionerror />
<s:form action="userImage" method="post" enctype="multipart/form-data">
    <s:file name="userImage" label="User Image" size="10"/>
    <s:submit value="Upload" align="center" />
</s:form>
</body>
</html>

There are couple of points worth noting in the above example. First of all, the form’s enctype is set to multipart/form-data. This should be set so that file uploads are handled successfully by the file upload interceptor. The next point noting is the form’s action method upload and the name of the file upload field – which is userImage. We need this information to create the action method and the struts configuration.

Next let us create a simple jsp file success.jsp to display the outcome of our file upload in case it becomes success. 

success.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Success: Upload User Image</title>
</head>
<body>
    <h2>Struts2 File Upload Example</h2>
    User Image: <s:property value="userImage"/>
    <br/>
    Content Type: <s:property value="userImageContentType"/>
    <br/>
    File Name: <s:property value="userImageFileName"/>
    <br/>
    Uploaded Image:
    <br/>
    <img src="<s:property value="userImageFileName"/>"/>
</body>
</html>

Following will be the result file error.jsp in case there is some error in uploading the file:

error.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Error</title>
</head>
<body>
There has been an error in uploading the file.
</body>
</html>

Create action class:

Next let us create a Java class called FileUploadAction.java which will take care of uploading file and storing that file at a secure location:

package com.dineshonjava.struts2.action.upload;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Dinesh Rajput
 *
 */
public class FileUploadAction extends ActionSupport implements ServletRequestAware {
 private static final long serialVersionUID = 1L;
 private File userImage;
 private String userImageContentType;
 private String userImageFileName;
 
 private HttpServletRequest servletRequest;
 
 public String execute() {
  try {
      String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
      System.out.println("Server path:" + filePath);
      File fileToCreate = new File(filePath, this.userImageFileName);
  
      FileUtils.copyFile(this.userImage, fileToCreate);
  } catch (Exception e) {
      e.printStackTrace();
      addActionError(e.getMessage());
 
      return INPUT;
  }
  return SUCCESS;
 }
 
 public File getUserImage() {
  return userImage;
 }
 
 public void setUserImage(File userImage) {
  this.userImage = userImage;
 }
 
 public String getUserImageContentType() {
  return userImageContentType;
 }
 
 public void setUserImageContentType(String userImageContentType) {
  this.userImageContentType = userImageContentType;
 }
 
 public String getUserImageFileName() {
  return userImageFileName;
 }
 
 public void setUserImageFileName(String userImageFileName) {
  this.userImageFileName = userImageFileName;
 }
 
 @Override
 public void setServletRequest(HttpServletRequest servletRequest) {
  this.servletRequest = servletRequest;
 }
}

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.
  • private String userImageFileName; -> This string will contain the file name of uploaded file.

The fields userImageContentType and userImageFileName are optional. If setter method of these fields are provided, struts2 will set the data. This is just to get some extra information of uploaded file. Also 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.
Also note in above action class, we have implemented interface org.apache.struts2.interceptor.ServletRequestAware. This is to get servletRequest object. We are using this path to save the uploaded file in execute() method. We have used FileUtil.copyFile() method of commons-io package to copy the uploaded file in root folder. This file will be retrieved in JSP page and displayed to user.

Configuration files:

Following are the Struts2 configuration properties that control file uploading process:

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
   <constant name="struts.devMode" value="true" />
   <package name="upload" extends="struts-default">
      <action name="userImage" class="com.dineshonjava.struts2.action.upload.FileUploadAction">
      <interceptor-ref name="fileUpload">
         <param name="maximumSize">2097152</param>
         <param name="allowedTypes">
             image/png,image/gif,image/jpeg,image/pjpeg
         </param>
       </interceptor-ref>
    <interceptor-ref name="defaultStack"></interceptor-ref>
    <result name="success">success.jsp</result>
    <result name="input">index.jsp</result>
     <result name="error">error.jsp</result>
 </action>
   </package>
 </struts>

Note that in above entry we have specified two parameter 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).

The file upload interceptor also does the validation and adds errors, these error messages are stored in the struts-messsages.properties file. The values of the messages can be overridden by providing the text for the following keys:

  1. struts.messages.error.uploading – error when uploading of file fails
  2. struts.messages.error.file.too.large – error occurs when file size is large
  3. struts.messages.error.content.type.not.allowed – when the content type is not allowed

Following is the content of web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2FileUpload</display-name>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Now Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access
URL http://localhost:8080/doj/index.jsp.
This will give you following screen:

Image Upload Screen in case of error-

Image Upload Screen on success-

Another Image Upload Screen on success-

Download Source Code+Libs
Struts2FileUpload.zip

 

<<Previous <<   || Index ||   >>Next >>

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago