struts2文件上传

  • 准备commons-fileupload和commons-io这两个jar包,并配置struts环境
  • 编写简单的上传页面
    部分代码
  • 编写testUpLoadAction代码
  1. 要定义一个私有属性File来接受页面上传的文件,属性名要和表达中的一致,上面表单使用的是text,所以这里也要要用text.
  2. 文件名的获取:定义私有字符串,表单中对应字段+FileName
  3. 文件类型的获取:定义私有字符串,表单中对应字段+ContentType
public class testAction extends ActionSupport{
    private File text;
    private String textFileName;
    
    public String execute() throws Exception {
        String realPath=ServletActionContext.getServletContext().getRealPath("here");
        System.out.println(realPath);
        if(text!=null){
            File saveFile=new File(new File(realPath),textFileName);
            if(!saveFile.getParentFile().exists()){
                 saveFile.getParentFile().mkdirs();
            }
            FileUtils.copyFile(text, saveFile);
            ActionContext.getContext().put("message", "send successfully");
        }       
        return "success";
    }

    
    
    public File getText() {
        return text;
    }

    public void setText(File text) {
        this.text = text;
    }

    public String getTextFileName() {
        return textFileName;
    }

    public void setTextFileName(String textFileName) {
        this.textFileName = textFileName;
    }
    
}
  • struts2默认上传大小是2M左右
    在配置文件中添加产量
  • 多文件上传
    只需要定义File类型的数组

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