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.
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 <s:file> 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 <s:file> file upload example</h1> <h4> File Name : <s:property value="fileUploadFileName"/> </h4> <h4> Content Type : <s:property value="fileUploadContentType"/> </h4> <h4> File : <s:property value="fileUpload"/> </h4> </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.
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.
4. Demo
http://localhost:8080/Struts2Example/fileUploadAction.action
Error message is prompt if you upload a file which is more than 10kb, or not a text file.
Upload a text file named “XWORK-LICENSE.txt”, file size : 5kb.
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
- Struts 2 file documentation
- http://struts.apache.org/2.0.14/docs/file-upload.html
- http://struts.apache.org/2.0.14/docs/how-do-we-upload-files.html
- http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html
- http://www.mkyong.com/struts/struts-file-upload-example/

is there any possibility to copy the files in their specific extension (txt,pdf…) not in tmp extension :(
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;
}
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”.
good
how to upload win rar file type?
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 ??
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?
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
hi swathi.
put this code before success in execute method;
path = request.getSession().getServletContext().getRealPath( “/” );
this sentence can get the server’s root path.I use it,and think it’s useful,thank you.
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)
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.
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