struts2文件上传

1、struts.xml定义文件大小限制
<constant name="struts.multipart.maxSize" value="10701096"/>
<package name="employee" namespace="/control/employee" extends="struts-default">
<action name="list_*" class="cn.itcast.action.HelloWorldAction" method="{1}">
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>

2、action获取文件
package cn.itcast.action;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;


public class HelloWorldAction {
    private File image;
    private String imageFileName;
    
    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    public String addUI(){
        return "success";
    }

    public String execute() throws Exception{
        
        String realpath = ServletActionContext.getServletContext().getRealPath("/images");
        System.out.println(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", "上传成功");
        }
        return "success";
    }
}

3、页面
<body>
    <form action="${pageContext.request.contextPath}/control/employee/list_execute.action" enctype="multipart/form-data" method="post">
        文件:<input type="file" name="image">
        <input type="submit" value="上传"/>
    </form>
  </body>

你可能感兴趣的:(struts2文件上传)