News Stay informed about the latest enterprise technology news and product updates.

A simple Struts 2 file upload example

 

There are a variety of complexities involved in the transfer of a file from a web browser to a remote application server. Fortunately for Java developers, most enterprise web frameworks provide file upload facilities that greatly simplify the task. In this Struts 2 file upload example, we will show you how the popular Apache Java web framework makes it possible for a remote client to transfer a local file through their browser and have it saved in a folder on the remote application server.

Struts File Upload

The basic steps involved in creating a Struts 2 file upload application are:

  1. Add the required commons-fileupload and commons-io dependencies to your Java web project
  2. Create a JSP that uses the Apache Struts form and file custom tags
  3. Code a Struts action class with setters that map to the name of the file, as specified s:file tag of the form
  4. In the execute method of the Struts action class, use standard Java IO packages to save the uploaded file
  5. Create a success JSP that informs the user the file was uploaded successfully

The JSP containing the special Struts tag that creates an HTML form element is the key to the Apache framework’s file upload capabilities. A prototypical Struts upload form looks as follows:

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<html>
<body>

  <s:form 
    action="fileupload" 
    method="post" 
    enctype="multipart/form-data">

      <s:file name="uploadedFile" label="File" />
      <s:submit />

  </s:form>

</body>
</html>

From one Struts file upload form to the next, the method of type post and the enctype of mutlipart/form-data will remain the same. The action attribute must map to the mapped name of the Struts action class that handles the request on the server, and the file name must map to a property declared in that action class. The coding of the corresponding action class is the next step in this Struts file upload tutorial.

Learn Apache Struts 2 Quickly

Here’s how to learn the fundamentals of Struts 2.5:

Follow these steps and you’ll be an Apache Struts 2 expert in no time!

The Struts file upload Action class

The name of the file in the Struts upload form above is uploadedFile. As a result, the action class that supports this form must have a setter method named setUploadedFile that takes a java.io.File object as an argument, and it must also have a setter method named setUploadedFileFileName that takes a String as an argument. The Struts framework will pass the uploaded file and its name to these methods. Note that the properties declared in the action do not have to map exactly to the setter names.

package com.mcnz.struts;

import java.io.*;
import java.util.*;
import java.util.stream.*;
import org.apache.commons.io.*;
import org.apache.struts2.convention.annotation.*;

import com.opensymphony.xwork2.ActionSupport;

@Action("/fileupload")
@Result(name = "success", location = "/results.jsp")
public class FileUploadAction extends ActionSupport {

  private File uploadedFile;
  private String uploadedFileName;
  private String localDirectory = "C:\\temp";

  public void setUploadedFile(File file) {
    uploadedFile = file;
  }

  public void setUploadedFileFileName(String name) {
    uploadedFileName = name;
  }

  public String execute() throws Exception {
    File localFile = new File(localDirectory, uploadedFileName);
    FileUtils.copyFile(uploadedFile, localFile);
    return SUCCESS;
  }

  /* Used to obtain a file listing for JSP display. */
  public Set<String> getFileList() {
    return Stream.of(new File(localDirectory).listFiles())
      .filter(file -> !file.isDirectory())
      .map(File::getName)
      .collect(Collectors.toSet());
  }

}

In the above Struts file upload action class, the execute method takes the uploaded file and saves it to the C:\temp folder.

A helper method named getFileList() is not necessary, but it has been added to allow the results page to list all of the files that currently reside in the upload folder.

Struts file upload confirmation page

The target of the action’s successful invocation is the results.jsp. This page need not be overly complex. By the time this page is invoked for rendering, the file has been succesfully uploaded. The following results.jsp would be more than enough to satisfy the current use case:

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ page contentType="text/html; charset=UTF-8"%>

<html>
<body>
<p> <s:property value="uploadedFileName"/> was uploaded successfully. </p>

</body>
</html>

Enhanced results page

If a user was to upload a file named image.jpg, the above results.jsp would simply print out “image.jpg was uploaded successfully.

To enhance the output, a getFileList() method was added to the action class. The inclusion of this method in the results.jsp, along with the original file upload form, would be a reasonable enhancement of the form, although the implementation is significantly more complicated. It’s worth it though:

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<html>
<body>

  <s:form action="fileupload" method="post" enctype="multipart/form-data">
    <s:file name="uploadedFile" label="File"/>
    <s:submit/>
  </s:form>

  <s:if test="%{uploadedFileName!=null}">
    <p><s:property value="uploadedFileName"/> was uploaded successfully.</p>
  </s:if>

  <h3>Directory listing</h3>

  <s:if test="%{fileList().isEmpty()}">
    <h3>No files in the directory</h3>
  </s:if>
  <s:else>
    <ul>
      <s:iterator value="fileList">
        <li><s:property /></li>
      </s:iterator>
    </ul>
  </s:else>

</body>
</html>

File upload Maven dependencies

Along with the standards Struts libraries, the file upload utilitiy also requires commons-io and commons-fileupload facilities. The following Maven dependencies must be added to your application to get the Struts 2 file upload facilities to work:

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.2.1</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>1.3.2</version>
</dependency>

With these dependencies added to your project, you can run the Struts file upload application and watch the temp directory get populated with resources every time you click the file upload button.

 

 

 

 

 

 

 

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

SearchAppArchitecture

SearchSoftwareQuality

SearchCloudComputing

SearchSecurity

SearchAWS

Close