Two implementations of struts2 single file upload

  • 2020-04-01 02:41:53
  • OfStack

There are 2 ways to simulate a single file upload, as shown below

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201401/201413152445743.jpg" >

The development steps are as follows:

1. Create a new web project and import the jars required for struts2 to upload files, as shown in the following figure

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201401/201413152550629.png" >

The directory structure

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201401/201413152726133.png" >

2. Create new Action

The first way


package com.ljq.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class UploadAction extends ActionSupport{

    private File image; //Uploaded file
    private String imageFileName; //The file name
    private String imageContentType; //The file type
    public String execute() throws Exception {
        String realpath = ServletActionContext.getServletContext().getRealPath("/images");
        //D:apache-tomcat-6.0.18webappsstruts2_uploadimages
        System.out.println("realpath: "+realpath);
        if (image != null) {
            File savefile = new File(new File(realpath), imageFileName);
            if (!savefile.getParentFile().exists())
                savefile.getParentFile().mkdirs();
            FileUtils.copyFile(image, savefile);
            ActionContext.getContext().put("message", " File uploaded successfully ");
        }
        return "success";
    }
    public File getImage() {
        return image;
    }
    public void setImage(File image) {
        this.image = image;
    }
    public String getImageFileName() {
        return imageFileName;
    }
    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }
    public String getImageContentType() {
        return imageContentType;
    }
    public void setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }
    
}

The second way


package com.ljq.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class UploadAction2 extends ActionSupport {
    //Encapsulates the properties of the upload file field
    private File image;
    //Encapsulates the properties of the upload file type
    private String imageContentType;
    //Encapsulates the property of the upload file name
    private String imageFileName;
    //Accept dependency injection properties
    private String savePath;
    @Override
    public String execute() {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            //Creates a file output stream
            System.out.println(getSavePath());
            fos = new FileOutputStream(getSavePath() + "\" + getImageFileName());
            //Set up file flow
            fis = new FileInputStream(getImage());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            System.out.println(" File upload failed ");
            e.printStackTrace();
        } finally {
            close(fos, fis);
        }
        return SUCCESS;
    }
    
    public String getSavePath() throws Exception{
        return ServletActionContext.getServletContext().getRealPath(savePath); 
    }
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }
    public File getImage() {
        return image;
    }
    public void setImage(File image) {
        this.image = image;
    }
    public String getImageContentType() {
        return imageContentType;
    }
    public void setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }
    public String getImageFileName() {
        return imageFileName;
    }
    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }
    private void close(FileOutputStream fos, FileInputStream fis) {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                System.out.println("FileInputStream Close the failure ");
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                System.out.println("FileOutputStream Close the failure ");
                e.printStackTrace();
            }
        }
    }
}

Struts.xml configuration file


<?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>
    <!--  This property specifies the requirements Struts2 The request suffix processed, the default value of this property is action , that is, all matches *.action Request by Struts2 To deal with. 
         If the user needs to specify multiple request suffixes, the suffixes are separated by an English comma ( , Separated).  -->
    <constant name="struts.action.extension" value="do" />
    <!--  Sets whether the browser caches static content , The default value is true( Used in production environment ), The development phase is best closed  -->
    <constant name="struts.serve.static.browserCache" value="false" />
    <!--  when struts The configuration file is modified , Does the system automatically reload the file , The default value is false( Used in production environment ), The development phase is best opened  -->
    <constant name="struts.configuration.xml.reload" value="true" />
    <!--  Use in development mode , This will print out more detailed error messages  -->
    <constant name="struts.devMode" value="true" />
    <!--  The default view theme  -->
    <constant name="struts.ui.theme" value="simple" />
    <!--<constant name="struts.objectFactory" value="spring" />-->
    <!-- To solve the code     -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <!--  Specifies the maximum number of bytes of files allowed to be uploaded. The default value is 2097152(2M) -->
    <constant name="struts.multipart.maxSize" value="10701096"/>
    <!--  Set up a temporary folder for uploading files , Use the default javax.servlet.context.tempdir -->
    <constant name="struts.multipart.saveDir " value="d:/tmp" />

         
    <package name="upload" namespace="/upload" extends="struts-default">
        <action name="*_upload" class="com.ljq.action.UploadAction" method="{1}">
            <result name="success">/WEB-INF/page/message.jsp</result>
        </action>
    </package>

    <package name="upload2" extends="struts-default">
        <action name="upload2" class="com.ljq.action.UploadAction2" method="execute">
            <!--  Dynamic setting savePath The attribute value  -->
            <param name="savePath">/images</param>
            <result name="success">/WEB-INF/page/message.jsp</result>
            <result name="input">/upload/upload.jsp</result>
            <interceptor-ref name="fileUpload">
                <!--  File filter  -->
                <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
                <!--  The file size ,  In bytes  -->
                <param name="maximumSize">1025956</param>
            </interceptor-ref>
            <!--  The default interceptor must be placed fileUpload After that, otherwise invalid  -->
            <interceptor-ref name="defaultStack" />
        </action>
    </package>
</struts>

Upload form page


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title> File upload </title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
    </head>
    <body>
        <!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
        <!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
        <form action="${pageContext.request.contextPath}/upload2/upload2.do" 
              enctype="multipart/form-data" method="post">
             file :<input type="file" name="image">
                <input type="submit" value=" upload " />
        </form>
        <br/>
        <s:fielderror />
    </body>
</html>

Display results page


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <title> Uploaded successfully </title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
  </head>

  <body>
     Upload successful! 
    <br/><br/>
    <!-- ${pageContext.request.contextPath} tomcat Deployment path, 
           Such as: D:apache-tomcat-6.0.18webappsstruts2_upload -->
    <img src="${pageContext.request.contextPath}/<s:property value="'images/'+imageFileName"/>">
    <s:debug></s:debug>
  </body>
</html>


Related articles: