<form action="hello/UploadAction_upload.action" enctype="multipart/form-data" method="post"> 单文件上传:<input name="myfile" value="请选择文件" type="file"><br> <input type="submit" > <form>
public class UploadAction extends ActionSupport{ //表单上提供的字段 private File myfile; //struts2在文件上传时提供的属性 private String myfileFileName;//上传的文件名。上传字段名称+FileName 注意大小写 private String myfileContentType;//上传文件的MIME类型。上传字段名称+ContentType 注意大小写 public String upload(){ String path= myfile.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)); //剪切:把临时文件剪切指定的位置,并且给他重命名。 注意:临时文件没有了 myfile.renameTo(new File(file,myfileFileName)); 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; } }
<!-- 文件上传 --> <action name="UploadAction_*" class="uploadfile.UploadAction" 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</param> </interceptor-ref> <result>../MyJsp.jsp</result> </action>
result: