Struts2 implements the file upload function

  • 2021-01-11 01:58:54
  • OfStack

HttpServletRequest of the Servlet 3.0 specification already provides methods to handle file uploads but this upload needs to be done in Servlet. Struts2, on the other hand, provides simpler encapsulation.

Struts2 default uses Common-FileUpload file upload framework of Jakarta, so to use Struts2 file upload function, you need to add two jar packages, namely commons-io-2.2.jar and commons-fileupload-1.3.1. es18EN.

Struts2 simple file upload example:

1. File upload page

In order to be able to upload the file, the form's method must be set to POST and enctype to multipart/form-data. When enctype is set to multipart/form-data, the browser will process the form data as a binary stream.


<%@ taglib prefix="s" uri="/struts-tags" %>
<%--
 Created by IntelliJ IDEA.
 User: Administrator
 Date: 2018/1/16
 Time: 14:06
 To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>Struts2  Simple file upload </title>
</head>
<body>
 <s:form action="file_upload" method="POST" enctype="multipart/form-data">
 <s:file name="upload" label=" Select the file "/>
 <s:submit value=" upload "/>
 </s:form>
</body>
</html>

2. ES39en to handle upload requests


/**
 * Description:Struts2 Simple file upload 
 * Author: Eleven
 * Date: 2018/1/24 10:39
 */
public class FileAction extends ActionSupport{

 // Upload a file 
 private File upload;
 // Upload file type 
 private String uploadContentType;
 // Upload file name 
 private String uploadFileName;

 // File upload allowed types in struts.xml The use of param The tag is set dynamically 
 private String allowTypes;

 public String page(){
 return "page";
 }

 public void upload() {

 // File upload: 
 //1. Read the contents of the file 
 //2. Writes the contents of the file to the specified file 
 try{
  System.out.println(" Type of file upload allowed ="+allowTypes);
  String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
  System.out.println(" The absolute path of the project ="+realPath);
  // Create a file save directory 
  new File(realPath).mkdir();
  File file = new File(realPath+"/"+uploadFileName);
  // The file is created if it does not exist 
  if(!file.exists()){
  file.createNewFile();
  }
  FileOutputStream out = new FileOutputStream(file);
  FileInputStream in = new FileInputStream(upload);
  byte[] buffer = new byte[1024];
  int len = 0;
  // Read and write   Each read 1kb  write 1kb
  while((len = in.read(buffer))>0){
  out.write(buffer,0,len);
  }
  System.out.println(" File uploaded successfully ...");
 }catch(Exception e){
  e.printStackTrace();
 }

 }

 public File getUpload() {
 return upload;
 }

 public void setUpload(File upload) {
 this.upload = upload;
 }

 public String getUploadContentType() {
 return uploadContentType;
 }

 public void setUploadContentType(String uploadContentType) {
 this.uploadContentType = uploadContentType;
 }

 public String getUploadFileName() {
 return uploadFileName;
 }

 public void setUploadFileName(String uploadFileName) {
 this.uploadFileName = uploadFileName;
 }

 public String getAllowTypes() {
 return allowTypes;
 }

 public void setAllowTypes(String allowTypes) {
 this.allowTypes = allowTypes;
 }
}

If the form contains a file field with an xxx attribute, three member variables are required in the corresponding Action to encapsulate the file field information.

The xxx member variable of type File encapsulates the contents of the corresponding file field.

The xxxFileName member variable of type String encapsulates the file name of the corresponding file field.

The xxxContentType member variable of type String encapsulates the file type of the file corresponding to the file field.

3. Configure struts. xml


<?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>
 <constant name="struts.enable.DynamicMethodInvocation" value="false" />
 <constant name="struts.devMode" value="true" />

 <package name="default" namespace="/" extends="struts-default">

 <!-- File upload -->
 <action name="file_*" class="eleven.action.FileAction" method="{1}">
  <result name="page">/WEB-INF/jsp/fileUpload.jsp</result>
  <!-- Dynamic setting action The properties of the , This example sets the types of files that are allowed to be uploaded, but action Not much is done in the program -->
  <param name="allowTypes">image/png,image/gif,image/jpeg</param>
 </action>

 </package>

</struts>

Interceptors implement file filtering

Struts2 provides an interceptor for file uploading, fileUpload. In order for this interceptor to work, the interceptor reference is configured in action.

When configuring the fileUpload interceptor, you can specify two parameters for it:

allowTypes: The file type allowed to be uploaded. Multiple file types are separated by English commas

maximumSize: Size of files allowed to be uploaded, in bytes.

When file filtering fails, the system automatically goes to the input logical view, so a logical view named input must be configured for this Action. In addition, the defaultStack interceptor reference must be explicitly configured for this Action.

struts.xml configuration file is as follows:


<?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>
 <constant name="struts.enable.DynamicMethodInvocation" value="false" />
 <constant name="struts.devMode" value="true" />

 <package name="default" namespace="/" extends="struts-default">

 <!-- File upload -->
 <action name="file_*" class="eleven.action.FileAction" method="{1}">
  <!-- configuration fileUpload The interceptor   And the configuration in defaultStack Before the interceptor stack -->
  <interceptor-ref name="fileUpload">
  <!-- The type of file that is allowed to upload -->
  <param name="allowedTypes">image/png,image/gif,image/jpeg</param>
  <!-- Upload file size allowed -->
  <param name="maximumSize">2000</param>
  </interceptor-ref>
  <!-- Configure the system default interceptor -->
  <interceptor-ref name="defaultStack"/>
  <!-- configuration input View the page -->
  <result name="input">/WEB-INF/jsp/input.jsp</result>

  <result name="page">/WEB-INF/jsp/fileUpload.jsp</result>
 </action>

 </package>

</struts>

The file upload interceptor configured above requires that the file upload type should only be an image file and the file size should not be larger than 2000 bytes. If the uploaded file is too large, or the type does not match, it will jump to the input logical view.


Related articles: