Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Struts2 file upload


May 15, 2021 Struts2


Table of contents


The Struts2 framework provides built-in support for file processing uploads based on Form-Based HTML File Uploads. When a file is uploaded, it is usually stored in a temporary directory, and then the Action class should process it or move it to a fixed directory to ensure that data is not lost.
Note: The server may have appropriate security policies that prevent you from writing to directories other than temporary directories and to directories that belong to Web applications.
Files can be uploaded in Struts via a predefined interceptor called FileUpload, which is available through the org.apache.struts2.interceptor.FileUploadInterceptor class and is included as part of the defaultStack. You'll also see how to use it to set various parameters .xml in the struts file.

Create a view file

You need to browse and upload selected files when you create a view. So let's start with the HTML upload form and create an index that allows users to upload files .jsp:

<%@ 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>
<title>File Upload</title>
</head>
<body>
   <form action="upload" method="post" enctype="multipart/form-data">
      <label for="myFile">Upload your file</label>
      <input type="file" name="myFile" />
      <input type="submit" value="Upload"/>
   </form>
</body>
</html>

There are a few points worth noting in the example above. F irst, the form's enctype is set to multipart/form-data, which must be set for the file upload interceptor to successfully process the file upload. T hen be aware of the form's action method upload and the name of the file upload field (myFile). We need this information to create action methods and struts configurations.
Next, let's create a simple jsp file .jsp to show the results of our successful file upload.

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Success</title>
</head>
<body>
You have successfully uploaded <s:property value="myFileFileName"/>
</body>
</html>

Here's the resulting .jsp error, which you'll use if you upload an error:

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Error</title>
</head>
<body>
There has been an error in uploading the file.
</body>
</html>

Create an Action class

Next, let's create a Java class called uploadFile .java, which will be responsible for uploading files and storing them in a secure location:

package cn.w3cschool.struts2;

import java.io.File;
import org.apache.commons.io.FileUtils;
import java.io.IOException; 

import com.opensymphony.xwork2.ActionSupport;

public class uploadFile extends ActionSupport{
   private File myFile;
   private String myFileContentType;
   private String myFileFileName;
   private String destPath;

   public String execute()
   {
      /* Copy file to a safe location */
      destPath = "C:/apache-tomcat-6.0.33/work/";

      try{
     	 System.out.println("Src File name: " + myFile);
     	 System.out.println("Dst File name: " + myFileFileName);
     	    	 
     	 File destFile  = new File(destPath, myFileFileName);
    	 FileUtils.copyFile(myFile, destFile);
  
      }catch(IOException e){
         e.printStackTrace();
         return ERROR;
      }

      return SUCCESS;
   }
   public File getMyFile() {
      return myFile;
   }
   public void setMyFile(File myFile) {
      this.myFile = myFile;
   }
   public String getMyFileContentType() {
      return myFileContentType;
   }
   public void setMyFileContentType(String myFileContentType) {
      this.myFileContentType = myFileContentType;
   }
   public String getMyFileFileName() {
      return myFileFileName;
   }
   public void setMyFileFileName(String myFileFileName) {
      this.myFileFileName = myFileFileName;
   }
}

UploadFile .java is a very simple class. I t's important to note that fileUpload interceptors and Parameters interceptors take on all the heavy workload for us. B y default, fileUpload interceptors give you three parameters, each named as follows:

  • File Name Parameters - This is the actual file that the user has uploaded. In this case it would be "myFile."

  • ContentType - This is the content type of the uploaded file. In this case, it would be "myFileContentType."

  • FileName - This is the name of the uploaded file. In this case, it would be "myFileFileName."

Thanks to the Struts interceptor, all three parameters are available to us. W hat we're going to do is create three parameters with the correct name in the Action class and make them automatically connected. S o, in the example above, we have three parameters and an action method. I f all goes well, return "success" or "error".

Profile

Here are the Struts2 configuration properties that control the file upload process:

Serial number Properties and descriptions
1 struts.multipart.maxSize

The maximum acceptable upload of files, in bytes, with a default value of 250M.

2 struts.multipart.parser

The library used to upload multi-part forms, which defaults to jakarta.

3 struts.multipart.saveDir

Where temporary files are stored, the default is javax.servlet.context.tempdir.

You can change any of these settings .xml the application's struts file using the constant tag, and we can look at the following examples of .xml struts:

<?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.multipart.maxSize" value="1000000" />

   <package name="helloworld" extends="struts-default">
   <action name="upload" class="cn.w3cschool.struts2.uploadFile">
       <result name="success">/success.jsp</result>
       <result name="error">/error.jsp</result>
   </action>
   </package>
</struts>

Because the FileUpload interceptor is part of the defaultStack interceptor, we don't need to configure it accurately, but you can add the tag to the . F ileUpload interceptors have two parameters: maximumSize and allowedTypes. T he maximumSize parameter is the maximum allowed file size set (about 2MB by default). T he allowedTypes parameter is a comma-separated list of allowed content (MIME) types, as follows:

   <action name="upload" class="cn.w3cschool.struts2.uploadFile">
       <interceptor-ref name="basicStack">
       <interceptor-ref name="fileUpload">
           <param name="allowedTypes">image/jpeg,image/gif</param>
       </interceptor-ref>
       <result name="success">/success.jsp</result>
       <result name="error">/error.jsp</result>
   </action>

Here's .xml the web file:

<?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>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

Now right-click on the project name, and then click "Export" and "WAR File" to create a WAR file. T he WAR file is then deployed in Tomcat's webapps directory. F inally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/upload.jsp display the following interface:

Struts2 file upload

Now use the browse button to select a file "Contacts.txt" and then click the upload button to upload the file to the server and you will see the following page. T he files you upload should be saved under C: .apache-tomcat-6.0.33.work.

Struts2 file upload

Note: FileUpload Interceptor automatically deletes uploaded files, so you must programmatically save the uploaded files somewhere before they are deleted.

The error message

FileUplaod interceptors use several default error message keys:

Serial number Error message keys and instructions
1 struts.messages.error.uploading

A general error occurred when the file could not be uploaded.

2 struts.messages.error.file.too.large

Occurs when the uploaded file is too large (specified by maximSize).

3 struts.messages.error.content.type.not.allowed

Occurs when the uploaded file does not match the specified expected content type.

You can override these message texts in the WebContent/WEB-INF/classes/messages.properties resource file.