struts2的多个文件上传
成功效果图:
上篇文章描述了单个文件的上传和配置,下面主要讲解下不同的地方:
index.jsp
<head> <script type="text/javascript"> function check(){ var file = document.getElementsByName("file"); var filename = document.getElementsByName("fileName"); var filetype = document.getElementsByName("fileType"); for(var i =0;i<file.length;i++){ if(file[i].value !=""){ var f = file[i].value ; var type = f.substr(f.lastIndexOf(".")).toLowerCase(); var name = f.substr(f.lastIndexOf("\\")); filename[i].value = name; filetype[i].value = type; }else{ alert("请选择文件"); return false; } } return true; } </script> </head> <body> <p>stuts 2 多文件上传实例 </p> ${requestScope.typeError} <form action="/uploadMore.do" method="post" enctype="multipart/form-data" onsubmit="return check();"> 上传文件1:<input type="file" name="file" /><br> <input type="hidden" name="fileType"/><br> <input type="hidden" name="fileName"/><br> 上传文件2:<input type="file" name="file" /><br> <input type="hidden" name="fileType"/><br> <input type="hidden" name="fileName"/><br> <input type="submit" value="提交"/> </form> </body>
struts.xml
<package name="uploadMoreFile" extends="struts-default"> <!--多文件上传 --> <action name="uploadMore" class="com.nn.upload.UploadMoreAction" method="uploadMore"> <interceptor-ref name="fileUpload"> <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/pjpeg</param> </interceptor-ref> <interceptor-ref name="defaultStack"/> <param name="savePath">/upload</param> <!-- 保存的真实路径 --> <result name="success">/successMore.jsp</result> <result name="input">/index.jsp</result> </action> </package>
UploadMoreAction.java
public class UploadMoreAction extends ActionSupport { private File[] file; private String[] fileName; private String[] fileType; public String uploadMore(){ String realpath = ServletActionContext.getServletContext().getRealPath("/upload"); if (this.file.length > 0) { String[] name = this.getFileName(); for(int i =0;i<file.length;i++){ SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); name[i] = df.format(new Date())+name[i].substring(1); //获取文件名称,去掉\,并添加时间 File savefile = new File(new File(realpath), name[i]); if (!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs(); try { FileUtils.copyFile(file[i], savefile); } catch (IOException e) { e.printStackTrace(); } ActionContext.getContext().put("message", "文件上传成功!"); } //this.setFileName(name); } return "success"; }
}
successMore.jsp
<body> ${requestScope.message}<br> <s:iterator value="fileName" status="stuts"> 文件名称: <s:property value="fileName[#stuts.index]"/><br> 文件为: <img src="${pageContext.request.contextPath}/<s:property value="'upload/'+fileName[#stuts.index]"/>"><br> </s:iterator> <s:debug></s:debug> </body>