<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<p>In this example you will learn how to do file upload with the help of the built-in <i><b>FileUploadInterceptor</b></i>. 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<i><b> multipart/form-data</b></i> and the HTTP method should be set to post. The <i><b>index.jsp</b></i> page contains the following code.</p>
<p>Create two JSP file in <b>WebRoot </b>folder.<b> index.jsp </b>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<b> success.jsp </b>file where File details will be displayed. Copy following code into it.</p>
</div>
<h2><b>index.jsp</b></h2>
<pre class="highlight"><;%@ 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>; 
</pre>
</div>
<div id="ads-id" align="center"></div>
<p>There are couple of points worth noting in the above example. First of all, the form&#8217;s enctype is set to <b>multipart/form-data</b>. This should be set so that file uploads are handled successfully by the file upload interceptor. The next point noting is the form&#8217;s action method upload and the name of the file upload field &#8211; which is <b>userImage</b>. We need this information to create the action method and the struts configuration.</p>
<p>Next let us create a simple jsp file <b>success.jsp</b> to display the outcome of our file upload in case it becomes success.<b> </b></p>
<h2><b>success.jsp</b></h2>
<pre class="highlight"><;%@ 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>; 
</pre>
</div>
<p>Following will be the result file <b>error.jsp</b> in case there is some error in uploading the file:</p>
<h2><b>error.jsp</b></h2>
<pre class="highlight"><;%@ 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>; 
</pre>
</div>
<h2><b>Create action class:</b></h2>
<p>Next let us create a Java class called <b>FileUploadAction.java</b> which will take care of uploading file and storing that file at a secure location:</p>
<pre class="highlight">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; 
 } 
} 
</pre>
<p>In above class file we have declared few attributes:</p>
<ul style="text-align: left;">
<li><b>private File userImage;</b> ->; This will store actual uploaded File</li>
<li><b>private String userImageContentType; ->; </b>This string will contain the Content Type of uploaded file.</li>
<li><b>private String userImageFileName; ->; </b>This string will contain the file name of uploaded file.</li>
</ul>
<p>The fields <b>userImageContentType </b>and <b>userImageFileName </b>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 <b>ContentType</b> and <b>FileName</b>. For example if the file attribute in action file is private File <b>uploadedFile</b>, the content type will be <b>uploadedFileContentType </b>and file name <b>uploadedFileFileName</b>.<br />
Also note in above action class, we have implemented interface <i><b>org.apache.struts2.interceptor.ServletRequestAware</b></i>. This is to get <b>servletRequest </b>object. We are using this path to save the uploaded file in <i><b>execute()</b></i> method. We have used <i><b>FileUtil.copyFile()</b></i> method of <b>commons-io</b> package to copy the uploaded file in root folder. This file will be retrieved in JSP page and displayed to user.</p>
<h2><b>Configuration files:</b></h2>
<p>Following are the Struts2 configuration properties that control file uploading process:</p>
</div>
<p><b>struts.xml</b></p>
<pre class="highlight"><;?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>; 
</pre>
<p>Note that in above entry we have specified two parameter to <b>fileUpload </b>interceptor, <b>maximumSize </b>and <b>allowedTypes</b>. These are optional parameters that we can specify to interceptor. The <b>maximumSize </b>param will set the maximum file size that can be uploaded. By default this is 2MB. And the <b>allowedTypes </b>param specify the allowed content types of file which can be uploaded. Here we have specified it to be an image file <b>(image/png,image/gif,image/jpeg,image/pjpeg).</b></p>
<p>The file upload interceptor also does the validation and adds errors, these error messages are stored in the <i><b>struts-messsages.properties</b></i> file. The values of the messages can be overridden by providing the text for the following keys:</p>
<ol style="text-align: left;">
<li><b>struts.messages.error.uploading</b> – error when uploading of file fails</li>
<li><b>struts.messages.error.file.too.large</b> – error occurs when file size is large</li>
<li><b>struts.messages.error.content.type.not.allowed</b> – when the content type is not allowed</li>
</ol>
</div>
<h2><b>Following is the content of <i>web.xml</i> file:</b></h2>
<pre class="highlight"><;?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>; 
</pre>
<p>Now Right click on the project name and click<b> Export >; WAR </b>File to create a War file. Then deploy this WAR in the Tomcat&#8217;s webapps directory. Finally, start Tomcat server and try to access<br />
<b>URL <i>http://localhost:8080/doj/index.jsp</i>. </b><br />
This will give you following screen:</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/07/11111.png" border="0" /></div>
<h2><b>Image Upload Screen in case of error-</b></h2>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/07/2222222.png" border="0" /></div>
</div>
<h2><b>Image Upload Screen on success-</b></h2>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/07/33333.png" border="0" /></div>
</div>
<h2><b>Another Image Upload Screen on success-</b></h2>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/07/44444.png" border="0" /></div>
<h2><b>Download Source Code+Libs</b><br />
<b><a href="https://sites.google.com/a/dineshonjava.com/dineshonjava/dineshonjava/Struts2FileUpload.zip?attredirects=0&;d=1" target="_blank" rel="noopener">Struts2FileUpload.zip</a></b></h2>
</div>
<p> ;</p>
<div style="background-color: pink; border-width: thin; text-align: center;"><b><;<;<a href="https://dineshonjava.com/struts-2-result-types/">Previous</a> <;<; || <a href="https://dineshonjava.com/struts-2-baby-step-to-learn/">Index </a>|| >;>;<a href="https://dineshonjava.com/struts-2-database-access/">Next</a> >;>;</b></div>
<p> ;</p>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/struts-2-result-types/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/struts-2-database-access/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '385'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…