<!-- 多文件上传 --> <action name="UploadAction2_*" class="uploadfile.UploadAction2" method="{1}"> <interceptor-ref name="defaultStack"> <!-- 允许文件类型 --> <!-- <param name="fileUpload.allowedTypes">image/jpg,image/pjpeg,image/png</param> --> <!-- 允许的文件后缀 --> <param name="fileUpload.allowedExtensions">jpg,jpeg,gif,java,png</param> </interceptor-ref> <result name="success" type="dispatcher">../MyJsp.jsp</result> </action>
public class UploadAction2 extends ActionSupport{ //表单上提供的字段 private File[] myfile; //struts2在文件上传时提供的属性 private String[] myfileFileName;//上传的文件名。上传字段名称+FileName 注意大小写 private String[] myfileContentType;//上传文件的MIME类型。上传字段名称+ContentType 注意大小写 public String upload(){ for (int i = 0; i < myfile.length; i++) { String path= myfile[i].getAbsolutePath(); System.out.println("临时文件路径:"+path); System.out.println("文件名:"+myfileFileName); System.out.println("文件类型:"+myfileContentType); } //1.拿到ServletContext ServletContext servletContext = ServletActionContext.getServletContext(); //2.调用realPath方法,获取根据一个虚拟目录得到的真实目录 String realPath = servletContext.getRealPath("/WEB-INF/file"); System.out.println(realPath); //3.如果这个真实的目录不存在,需要创建 File file = new File(realPath ); if(!file.exists()){ file.mkdirs(); } //4.把文件存过去 //拷贝:把文件的临时文件复制到指定的位置。注意:临时文件还在 //FileUtils.copyFile(myfile, new File(file,myfileFileName)); //剪切:把临时文件剪切指定的位置,并且给他重命名。 注意:临时文件没有了 for (int i = 0; i < myfile.length; i++) { myfile[i].renameTo(new File(file,myfileFileName[i])); } return SUCCESS; } public File[] getMyfile() { return myfile; } public void setMyfile(File[] myfile) { this.myfile = myfile; } public String[] getMyfileFileName() { return myfileFileName; } public void setMyfileFileName(String[] myfileFileName) { this.myfileFileName = myfileFileName; } public String[] getMyfileContentType() { return myfileContentType; } public void setMyfileContentType(String[] myfileContentType) { this.myfileContentType = myfileContentType; } }
<form action="hello/UploadAction2_upload.action" enctype="multipart/form-data" method="post"> 文件1:<input name="myfile" value="请选择文件" type="file"><br> 文件2:<input name="myfile" value="请选择文件" type="file"><br> <input type="submit" > <form>
result: