Struts 2 file upload example

In Struts 2, the <s:file> tag is used to create a HTML file upload component to allow users select file from their local disk and upload it to the server. In this tutorial, you will create a JSP page with file upload component, set the maximum size and allow content type of the upload file, and display the uploaded file details.

1. Action class

Action class for the file upload, declare a “File” variable to store the user uploaded file, two String variables to store the file name and content type. The “fileUpload interceptor” will auto inject the uploaded file detail via set”X”ContentType() and set”X”FileName(), make sure the method name is spell correctly.

P.S X is the variable to store the uploaded file.

The file upload function is depends on the “fileUpload Interceptor“, make sure it is included in the Action’s stack. The lucky is, the default stack is already includes the “fileUpload Interceptor“.

FileUploadAction.java

package com.mkyong.common.action;
 
import java.io.File;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class FileUploadAction extends ActionSupport{
 
	private File fileUpload;
	private String fileUploadContentType;
	private String fileUploadFileName;
 
	public String getFileUploadContentType() {
		return fileUploadContentType;
	}
 
	public void setFileUploadContentType(String fileUploadContentType) {
		this.fileUploadContentType = fileUploadContentType;
	}
 
	public String getFileUploadFileName() {
		return fileUploadFileName;
	}
 
	public void setFileUploadFileName(String fileUploadFileName) {
		this.fileUploadFileName = fileUploadFileName;
	}
 
	public File getFileUpload() {
		return fileUpload;
	}
 
	public void setFileUpload(File fileUpload) {
		this.fileUpload = fileUpload;
	}
 
	public String execute() throws Exception{
 
		return SUCCESS;
 
	}
 
	public String display() {
		return NONE;
	}
 
}

2. Result Page

Use <s:file> tag to render a file upload component, and set the form enctype type to “multipart/form-data”.

fileupload.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>
 
<body>
<h1>Struts 2 &lt;s:file&gt; file upload example</h1>
 
<s:form action="resultAction" namespace="/" 
method="POST" enctype="multipart/form-data">
 
<s:file name="fileUpload" label="Select a File to upload" size="40" />
 
<s:submit value="submit" name="submit" />
 
</s:form>
 
</body>
</html>

result.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
 
<body>
<h1>Struts 2 &lt;s:file&gt; file upload example</h1>
 
<h2>
   File Name : <s:property value="fileUploadFileName"/> 
</h2> 
 
<h2>
   Content Type : <s:property value="fileUploadContentType"/> 
</h2> 
 
<h2>
   File : <s:property value="fileUpload"/> 
</h2> 
 
</body>
</html>

3. struts.xml

Link it all ~

<?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" />
 	<constant name="struts.custom.i18n.resources" value="global" />
 
	<package name="default" namespace="/" extends="struts-default">
 
	<action name="fileUploadAction" 
	    class="com.mkyong.common.action.FileUploadAction" method="display">
	    <result name="none">pages/fileupload.jsp</result>
	</action>
 
	<action name="resultAction" class="com.mkyong.common.action.FileUploadAction">
	    <interceptor-ref name="exception"/>
            <interceptor-ref name="i18n"/>
            <interceptor-ref name="fileUpload">
       		<param name="allowedTypes">text/plain</param>
       		<param name="maximumSize">10240</param>
  	    </interceptor-ref> 
            <interceptor-ref name="params">
                <param name="excludeParams">dojo\..*,^struts\..*</param>
            </interceptor-ref>
            <interceptor-ref name="validation">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
            <interceptor-ref name="workflow">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
 
	    <result name="success">pages/result.jsp</result>
	    <result name="input">pages/fileupload.jsp</result>
 
	</action>
   </package>	
</struts>

File Size Limits
In this example, you set the upload file size limit via “fileUpload interceptor“, this value is count in bytes. In this case, the maximum size of the upload file is 10kb.

The default maximum file size of the upload file is 2MB

File Types
You can set the allow file type via “fileUpload interceptor” as well. In this case, the upload file only accept the “text/plain” content type.

In Struts 2, there are may ways to lead same Rome, make sure you check this Struts 2 file upload documentation.

4. Demo

http://localhost:8080/Struts2Example/fileUploadAction.action

Struts 2 file upload example

Error message is prompt if you upload a file which is more than 10kb, or not a text file.

Struts 2 file upload error page

Upload a text file named “XWORK-LICENSE.txt”, file size : 5kb.

Struts 2 file upload example

The uploaded file will be treat as a temporary file, with a long random file name, upload__376584a7_12981122379__8000_00000010.tmp. Make sure you copy this temp file to somewhere else. Read FileUtils documentation to copy files easily.

Reference

  1. Struts 2 file documentation
  2. http://struts.apache.org/2.0.14/docs/file-upload.html
  3. http://struts.apache.org/2.0.14/docs/how-do-we-upload-files.html
  4. http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html
  5. http://www.mkyong.com/struts/struts-file-upload-example/
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Dayanand C Adep

    Sir,

    i want to upload pdf using servlet & jsp

  • Satish

    Very good article.

  • Latifa

    is there any possibility to copy the files in their specific extension (txt,pdf…) not in tmp extension :(

    • Ganeshan

      can copy the file by…….

      public String execute() throws Exception
      {
      try {
      String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”);
      System.out.println(“Server path:” + filePath);
      System.out.println(this.getUserImageFileName());
      File fileToCreate = new File(filePath, this.userImageFileName);

      FileUtils.copyFile(this.userImage, fileToCreate);
      } catch (Exception e) {
      e.printStackTrace();
      addActionError(e.getMessage());

      return INPUT;
      }
      return SUCCESS;
      }

  • sahar

    Hi. thanks for your beautiful website.
    when i run this source code, i see error : “There is no Action mapped for namespace / and action name”.

  • adi

    good

  • knet

    how to upload win rar file type?

  • Ashish

    I did the same thing , but when i am running this page for the first time , details of the file is not coming , but when i press the BACK button , and then upload the file again , then all the information come.
    What to do ??

  • Lionel

    I have a question related to this example:

    In more modern browsers, either the file path is stripped away, or “C:\FakePath\” is added to the file name. How can one ensure that the file will correctly submit with the file path being incorrect?

  • http://developerinjava.blogspot.com swathi

    Hi,
    I uploaded three image files,
    in server they are converting to .tmp files,
    i want to convert these .tmp files again to image files and i have to store these image files into folder..
    can u know how to convert .tmp files to image files

    • jalil

      hi swathi.
      put this code before success in execute method;

      path =  request.getSession().getServletContext().getRealPath( &quot;/&quot; );
        File fileToCreate =null;
      			 try {
      		            String filePath = path;		            
      		            fileToCreate = new File(filePath, this.fileUploadFileName);		 
      		            FileUtils.copyFile(this.fileUpload, fileToCreate);
      		        } catch (Exception e) {
      		            e.printStackTrace();
      		            addActionError(e.getMessage());
      		        }
      • zenxoyo

        path = request.getSession().getServletContext().getRealPath( “/” );
        this sentence can get the server’s root path.I use it,and think it’s useful,thank you.

  • ye wint

    When I run it on the apache Tomcat server, I found this error. How can I fix it, help me.
    ava.lang.RuntimeException: Unable to load bean org.apache.struts2.dispatcher.multipart.MultiPartRequest (jakarta) – [unknown location]
    com.opensymphony.xwork2.inject.ContainerBuilder$4.create(ContainerBuilder.java:136)
    com.opensymphony.xwork2.inject.ContainerImpl.getInstance(ContainerImpl.java:476)
    com.opensymphony.xwork2.inject.ContainerImpl.getInstance(ContainerImpl.java:486)
    com.opensymphony.xwork2.inject.ContainerImpl$9.call(ContainerImpl.java:517)
    com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:542)
    com.opensymphony.xwork2.inject.ContainerImpl.getInstance(ContainerImpl.java:515)
    org.apache.struts2.dispatcher.Dispatcher.wrapRequest(Dispatcher.java:697)
    org.apache.struts2.dispatcher.FilterDispatcher.prepareDispatcherAndWrapRequest(FilterDispatcher.java:330)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:390)

    • Mohiz Tank

      This is caused by missing dependencies.

      Copy
      commons-fileupload-1.1.1.jar
      commons-io-1.1.jar
      in the lib folder and add as the external jars.

      • Thank you so much

        Thank you so much. I was struggling with this issue for the last 6 hours.

  • http://xurls.info/mvti Adam

    Interesting post. I randomly happended to see your website when I was in the process of research on the internet. Anyway, just wanted to say I liked your website and continue doin what you’re doin. Also, dont forget, enjoy the adventure.. don’t focus too much on the final destination. See ya, Adam

  • Pingback: Struts 2 upload multiple files example()