This tutorial shows how to upload multiple files using single browse button in Struts2. There is another tutorial on Multiple Files Upload in Struts2 which uses multiple browse buttons for multiple file upload but this tutorial uses only one button for uploading multiple file upload in Struts2. We need to use just attribute multiple=”multiple” with <s:file/> tag for uploading multiple files using the single browse button.

I won’t explain much details in this tutorial but if you need more explaination then you can go through another tutorial Multiple Files Upload in Struts2.

Prerequisites

Eclipse
Tomcat v7
JDK 1.6
Struts2 jars

file upload example in struts

Now we will see step by step how to upload multiple files below.

1. Create Dynamic Web Project in Eclipse.

2. Put the required jar files into the lib directory under WEB-INF folder.

3. Create a index.jsp file under WebContent folder. The index.jsp file contains the following code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Multiple File Upload Example using Single Browse button - Struts2</title>
</head>
<body>
<!-- show error message only when error occurrs -->
<s:if test="hasActionErrors()">
<s:actionerror />
</s:if>
<!-- show success message only when file successfully uploads -->
<s:if test="hasActionMessages()">
<s:actionmessage />
</s:if>
<s:form action="uploadMultipleFile" method="post"
enctype="multipart/form-data">
<!-- input type file for file upload, make sure to set multiple="multiple" for multiple uploads -->
<s:file label="File" name="files" multiple="multiple"></s:file>
<s:submit value="Upload Files"></s:submit>
</s:form>
</body>
</html>

 

4. Modify deployment descriptor file – web.xml, as shown below

<?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"
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>struts2SingleBrowseButton</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</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>

 

5. Now create struts.xml file with the following source code and put it under src directory.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- upload max file size limit -->
<constant name="struts.multipart.maxSize" value="10485760" />
<package name="default" namespace="/" extends="struts-default">
<!-- file upload action -->
<action name="uploadMultipleFile" class="in.webtuts.actions.MultipleFileUploadAction">
<!-- redirect to input page for file upload again -->
<result name="success">/index.jsp</result>
<!-- input page for file upload -->
<result name="input">/index.jsp</result>
<interceptor-ref name="defaultStack">
<param name="maximumSize">10485760</param>
<!-- what type of files are allowed to be uploaded -->
<param name="allowedTypes">text/plain,image/jpeg,image/png,image/gif,image/pjpeg</param>
</interceptor-ref>
</action>
</package>
</struts>

 

6. Create Controller or Action file MultipleFileUploadAction.java with the following source code.

package in.webtuts.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.servlet.ServletContext;

import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

public class MultipleFileUploadAction extends ActionSupport implements
ServletContextAware {

/**
*
*/
private static final long serialVersionUID = 5109187855480607759L;

//input type file name - files
private File[] files;
//all uploaded file names
private String[] filesFileName;
//all uploaded files content type
private String[] filesContentType;
//servletcontext for getting the context
private ServletContext servletContext;

public File[] getFiles() {
return files;
}

public void setFiles(File[] files) {
this.files = files;
}

public String[] getFilesFileName() {
return filesFileName;
}

public void setFilesFileName(String[] filesFileName) {
this.filesFileName = filesFileName;
}

public String[] getFilesContentType() {
return filesContentType;
}

public void setFilesContentType(String[] filesContentType) {
this.filesContentType = filesContentType;
}

public ServletContext getServletContext() {
return servletContext;
}

@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}

@Override
public void validate() {
//check whether at least one file was selected for upload
if (null == files) {
addActionMessage("You must select at least one file!");
}
}

@Override
public String execute() throws Exception {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
File dir = new File(servletContext.getRealPath(""));
System.out.println("servletContext.getRealPath(\"\"): "
+ servletContext.getRealPath(""));
if (!dir.exists()) {
dir.mkdirs();
}

try {
for (int i = 0; i < files.length; i++) {
String targetPath = dir.getPath() + File.separator
+ filesFileName[i];
System.out.println("targetPath: " + targetPath);
File f = new File(targetPath);
fileInputStream = new FileInputStream(files[i]);
fileOutputStream = new FileOutputStream(f);
int c;
while ((c = fileInputStream.read()) != -1) {
fileOutputStream.write(c);
}
}
} catch (Exception e) {
addActionError("Error occurred during uploading the file!");
return INPUT;
} finally {
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
addActionMessage("File(s) successfully uploaded!");
return SUCCESS;
}
}

 

When application runs and home page opens in browser

multiple files upload using single browse button in struts2
When you submit the Upload Files button without selecting any file using the browse button

multiple files upload using single browse button in struts2
When file(s) is/are selected using the browse button and Upload Files button is submitted

multiple files upload using single browse button in struts2
You will get the following output in console once files are successfully uploaded

servletContext.getRealPath(""): D:\EclipseProj\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\struts2SingleBrowseButton
targetPath: D:\EclipseProj\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\struts2SingleBrowseButton\htaccess.txt
targetPath: D:\EclipseProj\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\struts2SingleBrowseButton\URLs.txt

 

Thank you for reading. Please do not forget to leave a comment if you have any query.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *