Struts2中实现多文件上传于下载

来源:互联网 发布:perl语言编程pdf 编辑:程序博客网 时间:2024/06/07 22:54

做web开发,经常要实现文件的上传功能,Struts2使用的是jakarta中的commons-fileupload-1.2.jar和commons-io-1.3.1.jar来实现文件上传的,所以必须将这两个包放入lib目录

 

实现文件上传必须将表单的提交方式设为post(默认为get),并将enctype设置为multipart/form-data.不然无法完成文件上传

那么现在咋们就开始实现文件上传吧

1、完成一个上传表单upload.jsp和下载页面down.jsp

<form action="upload_upload" method="post" enctype="multipart/form-data">  <input type="file" name="files"><br>  <input type="file" name="files"><br>  <input type="submit" value="上传"></form>
<s:iterator value="filesFileName" id="file">  <a href='down_down?filename=<s:property value="#file"/>'><s:property value="#file"/></a><br></s:iterator>



2、上传和下载Action

public class UploadAction extends ActionSupport{private File[] files;private String[] filesFileName;public File[] getFiles(){return files;}public void setFiles(File[] files){this.files = files;}public String[] getFilesFileName(){return filesFileName;}public void setFilesFileName(String[] filesFileName){this.filesFileName = filesFileName;}public String[] getFilesContentType(){return filesContentType;}public void setFilesContentType(String[] filesContentType){this.filesContentType = filesContentType;}private String[] filesContentType;public String upload(){System.out.println("upload方法执行了...............");String path=ServletActionContext.getServletContext().getRealPath("upload");System.out.println("paht==>"+path);FileInputStream is=null;FileOutputStream os=null;for(int i=0;i<files.length;i++){try{is=new FileInputStream(files[i]);os=new FileOutputStream(new File(path,filesFileName[i]));int len=-1;byte[]buffer=new byte[1024];while(-1!=(len=is.read(buffer))){os.write(buffer, 0, len);}is.close();os.close();} catch (FileNotFoundException e){// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e){// TODO Auto-generated catch blocke.printStackTrace();}}ServletActionContext.getRequest().getSession().setAttribute("filename", filesFileName);return "success";}}



 

public class DownAction extends ActionSupport{private String filename;public String getFilename(){return filename;}public void setFilename(String filename){try{this.filename = new String(filename.getBytes("iso-8859-1"),"utf-8");} catch (UnsupportedEncodingException e){// TODO Auto-generated catch blocke.printStackTrace();}}public InputStream getDownFile(){return ServletActionContext.getServletContext().getResourceAsStream("/upload/"+filename);}public String down(){return "success";}}


 

3、配置文件struts.xml

<action name="upload_*" class="com.action.UploadAction" method="{1}"> <result name="success">/result.jsp</result> <result name="input">/upload.jsp</result> </action>   <action name="down_*" class="com.action.DownAction" method="{1}"> <result type="stream"> <param name="inputName">downFile</param> <param name="contentDisposition">attachment;filename="${filename}"</param> </result> </action>


 

原创粉丝点击