使用struts2实现文件上传

action中

1 private File file;//文件
2 private String fileFileName;//文件名字 固定格式name+FileName
3 private String fileContentType;//文件类型 name+ContentType

Action中定义的File类型的成员变量file实际上指向的是临时目录(struts.multipart.saveDir键所指定的目录中,如果该键对应的目录不存在,那么就保存到javax.servlet.context.tempdir环境变量所指定的目录中)中的临时文件,然后在服务器端通过IO的方式将临时文件写入到指定的服务器端目录中。

上传多文件时,在客户端jsp页面中文件的name="file" name值都叫file

action

 1 private List<File> file;
 2 private List<String> fileFileName;
 3 private List<String> fileContentType;
 1 public String execute() throws Exception
 2 {
 3   for(int i=0;i<file.size();i++){
 4          InputStream is=new FileInputStream(file.get(i));
 5          String path=ServletActionContext.getRequest().getRealPath("/upload");
 6           File f=new File(path,fileFileName.get(i));
 7           OutputStream os=new FileOutputStream(f);
 8           byte[] buffer=new byte[400];
 9           int length=0;
10           while(-1!=(length=is.read(buffer))){
11                   os.write(buffer,0,length);
12 
13     }
14 is.close();
15 os.close();
16 
17   } 
return SUCCESS;
18 }

 struts.xml中可以设置fileUpload拦截器中设置最大上传的大小

<interceptor-ref name="fileUpload">

  <param name="maximumSize">1024*1024</param>

</interceptor-ref>

另一种方式:

struts.properties中

struts.multipart.maxSize=10485760

在xml中配置

struts.xml中

<constant name="struts.multipart.maxSize" value="1048576000"/>

原文地址:https://www.cnblogs.com/oldcownotGiveup/p/5378026.html