jsp\struts1.2\struts2 中文件上传

转载自:http://code-chris.iteye.com/blog/208781

刚刚做了三个文件上传的Demo

a.在jsp中简单利用Commons-fileupload组件实现
b.在struts1.2中实现
c.在sturts2中实现
现在把Code与大家分享一下..
注:此为三个简单Demo,仅供练习用,并没有做太多上传限制
如有兴趣可以自行查看相关文档说明

一. 在JSP环境中利用Commons-fileupload组件实现文件上传
   1.页面upload.jsp清单如下:
Java代码   收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2.   
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>The FileUpload Demo</title>  
  7.   </head>  
  8.     
  9.   <body>  
  10.     <form action="UploadFile" method="post" enctype="multipart/form-data">  
  11.         <p><input type="text" name="fileinfo" value="">文件介绍</p>  
  12.         <p><input type="file" name="myfile" value="浏览文件"></p>  
  13.         <p><input type="submit" value="上 传"></p>  
  14.     </form>  
  15.   </body>  
  16. </html>  

注意:在上传表单中,既有普通文本域也有文件上传域

2.FileUplaodServlet.java清单如下:
Java代码   收藏代码
  1. package org.chris.fileupload;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.util.Iterator;  
  6. import java.util.List;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.*;  
  10.   
  11. import org.apache.commons.fileupload.FileItem;  
  12. import org.apache.commons.fileupload.FileItemFactory;  
  13. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  14. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  15.   
  16. public class FileUplaodServlet extends HttpServlet {  
  17.   
  18.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  19.         doPost(request, response);  
  20.     }  
  21.   
  22.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  23.           
  24.         request.setCharacterEncoding("UTF-8");  
  25.           
  26.         //文件的上传部分  
  27.         boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
  28.           
  29.         if(isMultipart)  
  30.         {  
  31.             try {  
  32.                 FileItemFactory factory = new DiskFileItemFactory();  
  33.                 ServletFileUpload fileload = new ServletFileUpload(factory);  
  34.                   
  35. //               设置最大文件尺寸,这里是4MB      
  36.                 fileload.setSizeMax(4194304);  
  37.                 List<FileItem> files = fileload.parseRequest(request);  
  38.                 Iterator<FileItem> iterator = files.iterator();     
  39.                 while(iterator.hasNext())  
  40.                 {  
  41.                     FileItem item = iterator.next();  
  42.                     if(item.isFormField())  
  43.                     {  
  44.                         String name = item.getFieldName();  
  45.                         String value = item.getString();  
  46.                         System.out.println("表单域名为: " + name + "值为: " + value);  
  47.                     }else  
  48.                     {  
  49.                         //获得获得文件名,此文件名包括路径  
  50.                         String filename = item.getName();  
  51.                         if(filename != null)  
  52.                         {  
  53.                             File file = new File(filename);  
  54.                             //如果此文件存在  
  55.                             if(file.exists()){  
  56.                                 File filetoserver = new File("d:\\upload\\",file.getName());  
  57.                                 item.write(filetoserver);  
  58.                                 System.out.println("文件 " + filetoserver.getName() + " 上传成功!!");  
  59.                             }  
  60.                         }  
  61.                     }  
  62.                 }  
  63.             } catch (Exception e) {  
  64.                 System.out.println(e.getStackTrace());  
  65.             }  
  66.         }  
  67.     }  
  68. }  

3.web.xml清单如下:
Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4"   
  3.     xmlns="http://java.sun.com/xml/ns/j2ee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  7.       
  8.     <servlet>  
  9.         <servlet-name>UploadFileServlet</servlet-name>  
  10.         <servlet-class>  
  11.             org.chris.fileupload.FileUplaodServlet  
  12.         </servlet-class>  
  13.     </servlet>  
  14.   
  15.     <servlet-mapping>  
  16.         <servlet-name>UploadFileServlet</servlet-name>  
  17.         <url-pattern>/UploadFile</url-pattern>  
  18.     </servlet-mapping>  
  19.       
  20.     <welcome-file-list>  
  21.         <welcome-file>/Index.jsp</welcome-file>  
  22.     </welcome-file-list>  
  23.       
  24. </web-app>  


二.在strut1.2中实现
1.上传页面file.jsp 清单如下:
Java代码   收藏代码
  1. <%@ page language="java" pageEncoding="ISO-8859-1"%>  
  2. <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>   
  3. <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>  
  4.    
  5. <html>   
  6.     <head>  
  7.         <title>JSP for FileForm form</title>  
  8.     </head>  
  9.     <body>  
  10.         <html:form action="/file" enctype="multipart/form-data">  
  11.         <html:file property="file1"></html:file>  
  12.             <html:submit/><html:cancel/>  
  13.         </html:form>  
  14.     </body>  
  15. </html>  


2.FileAtion.java的清单如下:
Java代码   收藏代码
  1. /* 
  2.  * Generated by MyEclipse Struts 
  3.  * Template path: templates/java/JavaClass.vtl 
  4.  */  
  5. package action;  
  6.   
  7. import java.io.*;  
  8.   
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. import org.apache.struts.action.Action;  
  12. import org.apache.struts.action.ActionForm;  
  13. import org.apache.struts.action.ActionForward;  
  14. import org.apache.struts.action.ActionMapping;  
  15. import org.apache.struts.upload.FormFile;  
  16.   
  17. import form.FileForm;  
  18.   
  19. /**  
  20.  * @author Chris 
  21.  * Creation date: 6-27-2008 
  22.  *  
  23.  * XDoclet definition: 
  24.  * @struts.action path="/file" name="fileForm" input="/file.jsp" 
  25.  */  
  26. public class FileAction extends Action {  
  27.     /* 
  28.      * Generated Methods 
  29.      */  
  30.   
  31.     /**  
  32.      * Method execute 
  33.      * @param mapping 
  34.      * @param form 
  35.      * @param request 
  36.      * @param response 
  37.      * @return ActionForward 
  38.      */  
  39.     public ActionForward execute(ActionMapping mapping, ActionForm form,  
  40.             HttpServletRequest request, HttpServletResponse response) {  
  41.         FileForm fileForm = (FileForm) form;  
  42.         FormFile file1=fileForm.getFile1();  
  43.         if(file1!=null){  
  44.             //上传路径  
  45.             String dir=request.getSession(true).getServletContext().getRealPath("/upload");  
  46.             OutputStream fos=null;  
  47.             try {  
  48.                 fos=new FileOutputStream(dir+"/"+file1.getFileName());  
  49.                 fos.write(file1.getFileData(),0,file1.getFileSize());  
  50.                 fos.flush();  
  51.             } catch (Exception e) {  
  52.                 // TODO Auto-generated catch block  
  53.                 e.printStackTrace();  
  54.             }finally{  
  55.                 try{  
  56.                 fos.close();  
  57.                 }catch(Exception e){}  
  58.             }  
  59.         }  
  60.         //页面跳转  
  61.         return mapping.findForward("success");  
  62.     }  
  63. }  


3.FileForm.java的清单如下:
Java代码   收藏代码
  1. package form;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import org.apache.struts.action.ActionErrors;  
  5. import org.apache.struts.action.ActionForm;  
  6. import org.apache.struts.action.ActionMapping;  
  7. import org.apache.struts.upload.FormFile;  
  8.   
  9. /**  
  10.  * @author Chris 
  11.  * Creation date: 6-27-2008 
  12.  *  
  13.  * XDoclet definition: 
  14.  * @struts.form name="fileForm" 
  15.  */  
  16. public class FileForm extends ActionForm {  
  17.     /* 
  18.      * Generated Methods 
  19.      */  
  20.     private FormFile file1;  
  21.     /**  
  22.      * Method validate 
  23.      * @param mapping 
  24.      * @param request 
  25.      * @return ActionErrors 
  26.      */  
  27.     public ActionErrors validate(ActionMapping mapping,  
  28.             HttpServletRequest request) {  
  29.         // TODO Auto-generated method stub  
  30.         return null;  
  31.     }  
  32.   
  33.     /**  
  34.      * Method reset 
  35.      * @param mapping 
  36.      * @param request 
  37.      */  
  38.     public void reset(ActionMapping mapping, HttpServletRequest request) {  
  39.         // TODO Auto-generated method stub  
  40.     }  
  41.   
  42.     public FormFile getFile1() {  
  43.         return file1;  
  44.     }  
  45.   
  46.     public void setFile1(FormFile file1) {  
  47.         this.file1 = file1;  
  48.     }  
  49. }  

4.struts-config.xml的清单如下:
Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">  
  3.   
  4. <struts-config>  
  5.   <data-sources />  
  6.   <form-beans >  
  7.     <form-bean name="fileForm" type="form.FileForm" />  
  8.   
  9.   </form-beans>  
  10.   
  11.   <global-exceptions />  
  12.   <global-forwards />  
  13.   <action-mappings >  
  14.     <action  
  15.       attribute="fileForm"  
  16.       input="/file.jsp"  
  17.       name="fileForm"  
  18.       path="/file"  
  19.       type="action.FileAction"  
  20.       validate="false">  
  21.        <forward name="success" path="/file.jsp"></forward>  
  22.       </action>  
  23.   
  24.   </action-mappings>  
  25.   
  26.   <message-resources parameter="ApplicationResources" />  
  27. </struts-config>  

5.web.xml代码清单如下:
Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  3.   <servlet>  
  4.     <servlet-name>action</servlet-name>  
  5.     <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>  
  6.     <init-param>  
  7.       <param-name>config</param-name>  
  8.       <param-value>/WEB-INF/struts-config.xml</param-value>  
  9.     </init-param>  
  10.     <init-param>  
  11.       <param-name>debug</param-name>  
  12.       <param-value>3</param-value>  
  13.     </init-param>  
  14.     <init-param>  
  15.       <param-name>detail</param-name>  
  16.       <param-value>3</param-value>  
  17.     </init-param>  
  18.     <load-on-startup>0</load-on-startup>  
  19.   </servlet>  
  20.   <servlet-mapping>  
  21.     <servlet-name>action</servlet-name>  
  22.     <url-pattern>*.do</url-pattern>  
  23.   </servlet-mapping>  
  24. </web-app>  


三.在struts2中实现(以图片上传为例)
1.FileUpload.jsp代码清单如下:
Java代码   收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags" %>  
  3. <html>  
  4.   <head>  
  5.     <title>The FileUplaodDemo In Struts2</title>  
  6.   </head>  
  7.     
  8.   <body>  
  9.     <s:form action="fileUpload.action" method="POST" enctype="multipart/form-data">  
  10.         <s:file name="myFile" label="MyFile" ></s:file>  
  11.         <s:textfield name="caption" label="Caption"></s:textfield>  
  12.         <s:submit label="提交"></s:submit>  
  13.     </s:form>  
  14.   </body>  
  15. </html>  


2.ShowUpload.jsp的功能清单如下:
Java代码   收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags" %>  
  3. <html>  
  4.   <head>  
  5.     <title>ShowUpload</title>  
  6.   </head>  
  7.     
  8.   <body>  
  9.     <div style ="padding: 3px; border: solid 1px #cccccc; text-align: center" >   
  10.         <img src ='UploadImages/<s:property value ="imageFileName"/> '/>  
  11.         <br />   
  12.         <s:property value ="caption"/>   
  13.     </div >   
  14.   </body>  
  15. </html>  


3.FileUploadAction.java的代码清单如下 :
Java代码   收藏代码
  1. package com.chris;  
  2.   
  3. import java.io.*;  
  4. import java.util.Date;  
  5.   
  6. import org.apache.struts2.ServletActionContext;  
  7.   
  8.   
  9. import com.opensymphony.xwork2.ActionSupport;  
  10.   
  11. public class FileUploadAction extends ActionSupport{  
  12.   
  13.      private static final long serialVersionUID = 572146812454l ;  
  14.      private static final int BUFFER_SIZE = 16 * 1024 ;  
  15.       
  16.      //注意,文件上传时<s:file/>同时与myFile,myFileContentType,myFileFileName绑定  
  17.      //所以同时要提供myFileContentType,myFileFileName的set方法  
  18.        
  19.      private File myFile;   //上传文件  
  20.      private String contentType;//上传文件类型  
  21.      private String fileName;   //上传文件名  
  22.      private String imageFileName;  
  23.      private String caption;//文件说明,与页面属性绑定  
  24.       
  25.      public void setMyFileContentType(String contentType)  {  
  26.          System.out.println("contentType : " + contentType);  
  27.          this .contentType = contentType;  
  28.     }   
  29.       
  30.      public void setMyFileFileName(String fileName)  {  
  31.          System.out.println("FileName : " + fileName);  
  32.          this .fileName = fileName;  
  33.     }   
  34.           
  35.      public void setMyFile(File myFile)  {  
  36.          this .myFile = myFile;  
  37.     }   
  38.       
  39.      public String getImageFileName()  {  
  40.          return imageFileName;  
  41.     }   
  42.       
  43.      public String getCaption()  {  
  44.          return caption;  
  45.     }   
  46.    
  47.       public void setCaption(String caption)  {  
  48.          this .caption = caption;  
  49.     }   
  50.       
  51.      private static void copy(File src, File dst)  {  
  52.          try  {  
  53.             InputStream in = null ;  
  54.             OutputStream out = null ;  
  55.              try  {                  
  56.                 in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);  
  57.                 out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);  
  58.                  byte [] buffer = new byte [BUFFER_SIZE];  
  59.                  while (in.read(buffer) > 0 )  {  
  60.                     out.write(buffer);  
  61.                 }   
  62.              } finally  {  
  63.                  if ( null != in)  {  
  64.                     in.close();  
  65.                 }   
  66.                   if ( null != out)  {  
  67.                     out.close();  
  68.                 }   
  69.             }   
  70.          } catch (Exception e)  {  
  71.             e.printStackTrace();  
  72.         }   
  73.     }   
  74.       
  75.      private static String getExtention(String fileName)  {  
  76.          int pos = fileName.lastIndexOf(".");  
  77.          return fileName.substring(pos);  
  78.     }   
  79.    
  80.     @Override  
  81.      public String execute()      {          
  82.         imageFileName = new Date().getTime() + getExtention(fileName);  
  83.         File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages" ) + "/" + imageFileName);  
  84.         copy(myFile, imageFile);  
  85.          return SUCCESS;  
  86.     }  
  87. }  

注:此时仅为方便实现Action所以继承ActionSupport,并Overrider execute()方法
  在struts2中任何一个POJO都可以作为Action

4.struts.xml清单如下:
Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5. <struts>  
  6.     <package name="example" namespace="/" extends="struts-default">  
  7.         <action name="fileUpload" class="com.chris.FileUploadAction">  
  8.         <interceptor-ref name="fileUploadStack"/>  
  9.         <result>/ShowUpload.jsp</result>  
  10.         </action>  
  11.     </package>  
  12. </struts>  

5.web.xml清单如下:
Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4"   
  3.     xmlns="http://java.sun.com/xml/ns/j2ee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  7.     <filter >   
  8.         <filter-name > struts-cleanup </filter-name >   
  9.         <filter-class >   
  10.             org.apache.struts2.dispatcher.ActionContextCleanUp  
  11.         </filter-class >   
  12.     </filter >   
  13.      <filter-mapping >   
  14.         <filter-name > struts-cleanup </filter-name >   
  15.         <url-pattern > /* </url-pattern >   
  16.     </filter-mapping >  
  17.       
  18.     <filter>  
  19.         <filter-name>struts2</filter-name>  
  20.         <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  
  21.     </filter>  
  22.     <filter-mapping>  
  23.         <filter-name>struts2</filter-name>  
  24.         <url-pattern>/*</url-pattern>  
  25.     </filter-mapping>  
  26.   <welcome-file-list>  
  27.     <welcome-file>Index.jsp</welcome-file>  
  28.   </welcome-file-list>  
  29.     
  30. </web-app> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值