Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Struts2 Multiple File Upload

DZone's Guide to

Struts2 Multiple File Upload

Here's an awesome Struts2 tutorial on uploading multiple files. Check out how to use this handy Java EE web app.

· Java Zone
Free Resource

Learn how our document data model can map directly to how you program your app, and native database features like secondary indexes, geospatial and text search give you full access to your data. Brought to you in partnership with MongoDB.

To achieve this, there are some changes required on both client side and server side:

Multiple File Upload Using Struts 2,File Upload Using Struts 2,Upload Using Struts 2,Upload multiple files with Struts 2,multiple files with Struts 2,files with Struts 2,Upload files with Struts 2files with Struts 2


  • 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:
  1.    File X to String[] X or List<File> X
  2.    String XFileName to String[] XFileName or List<String> XFileName
  3.    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 upload multiple files example

The following example program demonstrates how to implement functionality to upload multiple files with Struts 2 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.xmlfile.

Let’s see how the example application is coded.

2. Write code for upload form

The upload form is implemented in the upload.jsp page as follows:

When running, the page looks like this:

<%@ 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>


On submitting of this form, the action uploadFile is invoked.

3. Write code for action class

Implement Struts 2’s action class in MultipleFilesUploadAction.java file as follows:

package com.geekonjava.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 2’s interceptor called fileUpload will fetch data for these variables through setters.
  • Value of the variable saveDirectory is set through corresponding setter by Struts 2’s 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.

For more >>>>>Geek On Java<<<<<

Discover when your data grows or your application performance demands increase, MongoDB Atlas allows you to scale out your deployment with an automated sharding process that ensures zero application downtime. Brought to you in partnership with MongoDB.

Topics:
struts2 ,j2ee ,struts2 application ,java

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}