Struts Multiple Files Upload Example
- Details
- Written by Nam Ha Minh
- Last Updated on 03 August 2019   |   Print Email
Table of Content:
- About the upload multiple files example
- Write code for upload form
- Write code for action class
- Write code for result page
- Configure struts.xml
- Configure web.xml
Based on the tutorial Upload files with Struts, this article extends the sample program to be able to upload multiple files at once. To achieve this, there are some changes required on both client side and server side:
- Client side: use multiple <s:file> tags that allow user to pick up as many files as needed.
- Server side: in the action class, modify type of the member variables from single object to an array or a list as follows:
- File X to String[] X or List<File> X
- String XFileName to String[] XFileName or List<String> XFileName
- String XContentType to String[] XContentType or List<String> XContentType
Where X is the name of the <s:file> tags in upload form, for example:
<s:file name="fileUpload" />
then X will be “fileUpload”. Hence in the action class:
File[] fileUpload;
String[] fileUploadFileName;
String[] fileUploadContentType;
or:
List<File> fileUpload;
List<String> fileUploadFileName;
List<String> fileUploadContentType;
And remember to create getters and setters for those variables properly.
1. About the Struts upload multiple files example
The following example program demonstrates how to implement functionality to upload multiple files with Struts framework. The application shows an upload form which allows user to pick up three files to upload at once. The uploaded files are copied into a location which is configured in application’s struts.xml file.
Let’s see how the example application is coded.
2. Write code for File upload form
The upload form is implemented in the upload.jsp page as follows:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!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 Files Upload with Struts2</title> </head> <body> <center> <h2>Pick multiple files to upload</h2> <s:form action="uploadFile" enctype="multipart/form-data" method="post"> <s:file name="fileUpload" label="Pick file #1" size="30"/> <s:file name="fileUpload" label="Pick file #2" size="30"/> <s:file name="fileUpload" label="Pick file #3" size="30"/> <br/> <s:submit value="Upload All" /> </s:form> </center> </body> </html>
When running, the page looks like this:
On submitting of this form, the action uploadFile is invoked.
3. Write code for Struts action class
Implement Struts action class in MultipleFilesUploadAction.java file as follows:
package net.codejava.struts; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class MultipleFilesUploadAction { private File[] fileUpload; private String[] fileUploadFileName; private String[] fileUploadContentType; /** * This is the path to save uploaded file, which is configured in struts.xml */ private String saveDirectory; public String doUpload() { // copy the uploaded files into pre-configured location for (int i = 0; i < fileUpload.length; i++) { File uploadedFile = fileUpload[i]; String fileName = fileUploadFileName[i]; File destFile = new File(saveDirectory + File.separator + fileName); try { FileUtils.copyFile(uploadedFile, destFile); } catch (IOException ex) { System.out.println("Could not copy file " + fileName); ex.printStackTrace(); } } return "success"; } public File[] getFileUpload() { return fileUpload; } public void setFileUpload(File[] fileUploads) { this.fileUpload = fileUploads; } public String[] getFileUploadFileName() { return fileUploadFileName; } public void setFileUploadFileName(String[] fileUploadFileNames) { this.fileUploadFileName = fileUploadFileNames; } public String[] getFileUploadContentType() { return fileUploadContentType; } public void setFileUploadContentType(String[] fileUploadContentTypes) { this.fileUploadContentType = fileUploadContentTypes; } public String getSaveDirectory() { return saveDirectory; } public void setSaveDirectory(String saveDir) { this.saveDirectory = saveDir; } }
In this POJO action class, we use three arrays to store uploaded files:
private File[] fileUpload; private String[] fileUploadFileName; private String[] fileUploadContentType;
- Note that the word “fileUpload” matches with value of name attribute of <s:file> tag in the upload.jsp file. Struts’ interceptor called fileUpload will fetch data for these variables through setters.
- Value of the variable saveDirectory is set through corresponding setter by Struts’ staticParams interceptor, and this value can be configured in struts.xml file.
- The action class’ entry method doUpload() copies the uploaded files from temporary directory to the location specified by the saveDirectory variable, then redirect to a “success” view which is the result page.
4. Write code for upload result page
The result page result.jsp - is pretty simple, which shows a successful message:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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>Upload result</title> </head> <body> <center> <h2>The files were uploaded successfully</h2> </center> </body> </html>
5. Configure struts.xml
We connect the upload form page, the action class and the result page through application’s struts.xmlfile as follows:
<?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.multipart.maxSize" value="20971520" /> <!-- 20MB --> <package name="fileUpload" extends="struts-default"> <action name="uploadFile" class="net.codejava.struts.MultipleFilesUploadAction" method="doUpload"> <param name="saveDirectory">E:/Test/Upload</param> <interceptor-ref name="fileUpload"> <param name="allowedTypes">*/*</param> <param name="maximumSize">4194304</param> <!-- 4MB --> </interceptor-ref> <interceptor-ref name="staticParams"/> <interceptor-ref name="params" /> <interceptor-ref name="validation" /> <interceptor-ref name="workflow" /> <result name="success" type="redirect">/result.jsp</result> <result name="input">/upload.jsp</result> </action> </package> </struts>
- Here, the interceptor fileUpload is configured to allow all file types can be uploaded, and maximum size for an individual file is 4MB.
- The constant struts.multipart.maxSize restricts maximum size allowed for a multipart request is 20MB. That means the total size of upload files cannot exceed 20MB.
- The parameter saveDirectory specifies where to copy uploaded files. The interceptor staticParams must be specified to fetch value of the parameter saveDirectory for the action class.
6. Configure web.xml
To enable Struts framework for the application, the web deployment descriptor file (web.xml) is configured as follows:
<?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>Struts2 Multiple Files Upload</display-name> <welcome-file-list> <welcome-file>upload.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>DispatcherFilter</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>DispatcherFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
With this configuration, Struts' dispatcher filter will intercept all requests, and the default page is the upload.jsp page.
Other Struts Tutorials:
- Introduction to Struts 2 framework
- Struts beginner tutorial (Eclipse + Tomcat + XML)
- Struts Beginner Tutorial with Annotations
- Struts beginner tutorial with Convention Plugin (zero-configuration)
- How to handle exceptions in Struts
- Struts Form Handling Tutorial
- Struts Form Validation Tutorial
- Send e-mail with attachments in Struts
- Struts File Download Tutorial
- Struts - Spring - Hibernate Integration Tutorial
Comments
There is Attachements section above. You can download the example project there.