代码如下

package com.ming;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

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

    @Override
    public String execute()
    {
        Logger logger = LogManager.getLogger();
        // 获取到Action执行的上下文
        destPath = ServletActionContext.getServletContext().getRealPath("/");
        // 拼接目录
        destPath = destPath + "upload/";
        // 新建文件
        File tmpFile = new File(destPath, new Date().toString() + this.myFileFileName);
        try{
            FileUtils.copyFile(myFile, tmpFile);
        }catch (Exception e){
            logger.info(e);
        }
        logger.info(myFileContentType);
        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;
    }
}

核心思路 是 获取到当前action上下文件,接着获取容器上下文,在进行绝对路径拼接,拼接完成以后,新建file文件,然后,文件内容写入即可.

配置文件

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.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="com.ming.uploadFile">
            <interceptor-ref name="defaultStack"/>
            <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>
    </package>
</struts>