Java开发过程中文件上传的各种方式全面总结

[size=x-large]到目前为止:我接触到的有关上传的类型有这么几种
JSP+Servlet的,Struts2的,Struts的,FTP的,ExtJs的,Flex的
最终还是建议看看,后面详细写的Struts2的上传文章最为实用

第一:JSP+Servlet上传
这个最基础的上传示例[其实也可以完全在JSP上进行处理]
我选用的包是Apache commons fileupload.jar
下载地址:http://jakarta.apache.org/commons/fileupload/

JSP页面具体代码
Html代码 
<span style="font-size: medium;"><span style="font-size: large;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<html>  
  <head>  
    <title>JSP+Servlet上传示例</title>  
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="This is my page">  
  </head>  
  <body>  
       <form action="upload.do" method="post" enctype="multipart/form-data">  
      <input type ="file" name="file1" id="file1" /><br/>  
      <input type ="file" name="file2" if="file2"/><br/>  
      <input type ="file" name="file3" id="file3"/><br/>  
       <input type="submit" value="上传" />   
       </form>  
  </body>  
</html></span></span>
 
上 面文件中有几个需要注意的地方就是
1. action="UploadServlet" 必须和后面的web.xml配置文件中对servlet映射必须保持一致.
2. method="POST" 这里必须为"POST"方式提交不能是"GET".
3. enctype="multipart/form-data" 这里是要提交的内容格式,表示你要提交的是数据流,而不是普通的表单
文本.
4. file1,file2,file3表示你要3个文件一起上传,你也可以一次只上传一个文件.

Servlet处理类程序
Java代码 
<span style="font-size: medium;"><span style="font-size: large;">package com.upload.test;  
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.apache.commons.fileupload.FileItemIterator;  
import org.apache.commons.fileupload.FileItemStream;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  
import org.apache.commons.fileupload.util.Streams;  
  
public class UploadServlet extends HttpServlet {  
      
    File tmpDir = null;//初始化上传文件的临时存放目录  
    File saveDir = null;//初始化上传文件后的保存目录  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        this.doPost(request, response);  
    }  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        request.setCharacterEncoding("utf-8");  
        try{  
            if(ServletFileUpload.isMultipartContent(request)){  
            DiskFileItemFactory dff = new DiskFileItemFactory();//创建该对象  
            dff.setRepository(tmpDir);// 指定上传文件的临时目录  
            dff.setSizeThreshold(1024000);//指定在内存中缓存数据大小,单位为byte  
            ServletFileUpload sfu = new ServletFileUpload(dff);//创建该对象  
            sfu.setFileSizeMax(5000000);// 指定单个上传文件的最大尺寸  
            sfu.setSizeMax(10000000);//指定一次上传多个文件的 总尺寸  
            FileItemIterator fii = sfu.getItemIterator(request);//解析request 请求,  
  
并返回FileItemIterator集合  
            while(fii.hasNext()){  
            FileItemStream fis = fii.next();//从集合中获得一个文件流  
            if(!fis.isFormField() && fis.getName().length()>0){//过滤掉表单中非文件  
  
域  
            String fileName = fis.getName().substring(fis.getName().lastIndexOf  
  
("\\"));//获得上传文件的文件名  
            BufferedInputStream in = new BufferedInputStream(fis.openStream());//获  
  
得文件输入流  
            BufferedOutputStream out = new BufferedOutputStream(new   
  
FileOutputStream(new File(saveDir+fileName)));//获得文件输出流  
            Streams.copy(in, out, true);//开始把文件写到你指定的上传文件夹  
            }  
            }  
            response.getWriter().println("File upload successfully!!!");//终于成功了  
  
,还不到你的上传文件中看看,你要的东西都到齐了吗  
            }  
            }catch(Exception e){  
            e.printStackTrace();  
            }  
    }  
    @Override  
    public void init() throws ServletException {  
        super.init();  
        /* 对上传文件夹和临时文件夹进行初始化 
        * 
        */  
        String tmpPath = "c:\\tmpdir";  
        String savePath = "c:\\updir";  
        tmpDir = new File(tmpPath);  
        saveDir = new File(savePath);  
        if(!tmpDir.isDirectory())  
        tmpDir.mkdir();  
        if(!saveDir.isDirectory())  
        saveDir.mkdir();  
  
    }  
      
}</span></span>  



第二:struts2的上传吧
upload.jsp-----------

Html代码 
<span style="font-size: medium;"><span style="font-size: large;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
<%@ taglib uri="/struts-tags" prefix="s"%>  
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()  
  
+path+"/";  
%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
  </head>    
<body>  
 <s:form action="test.action" method="POST" enctype="multipart/form-data">  
 <s:file label="选择文件" name="upFile"></s:file>  
 <s:submit label="上传" />  
 </s:form>  
</body>  
</html>  

</span></span> 
UploadAction----------------
Java代码 
<span style="font-size: medium;"><span style="font-size: large;">package com.upload.test;  
  
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
  
import com.opensymphony.xwork2.ActionSupport;  
  
public class UploadAction extends ActionSupport {  
    private File   upFile;  
     private String upFileFileName;  //上传的文件名 (1.系统自动注入  2.变量命名有规则: 前台  
  
对象名+"FileName")  
     private String upFileContentType; //文件类型           (1.系统自动注入  2.变量命名有规  
  
则: 前台对象名+"ContentType")  
     private String savePath;  
       
       
     @Override  
     public String execute() throws Exception {  
      System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxx");  
      String path = "c:/" + upFileFileName;  
      BufferedInputStream bis = null;  
      BufferedOutputStream bos = null;  
        
      try{  
       bis = new BufferedInputStream(new FileInputStream(upFile));  
       bos = new BufferedOutputStream(new FileOutputStream(path));  
       byte[] buf = new byte[(int)upFile.length()];  
       int len = 0;  
       while(((len=bis.read(buf))!=-1)){  
        bos.write(buf, 0, len);  
       }  
      }catch(Exception e){  
       e.printStackTrace();  
      }finally{  
        try{  
          if(bos!=null){  
           bos.close();  
          }  
          if(bis!=null){  
           bis.close();  
          }  
        }catch(Exception e){  
       bos = null;  
       bis = null;  
        }  
      }  
              
      return SUCCESS;  
     }  
  
       
     public File getUpFile() {  
      return upFile;  
     }  
  
     public void setUpFile(File upFile) {  
      this.upFile = upFile;  
     }  
  
     public String getUpFileFileName() {  
      return upFileFileName;  
     }  
  
     public void setUpFileFileName(String upFileFileName) {  
      this.upFileFileName = upFileFileName;  
     }  
  
     public String getUpFileContentType() {  
      return upFileContentType;  
     }  
  
     public void setUpFileContentType(String upFileContentType) {  
      this.upFileContentType = upFileContentType;  
     }  
  
     public String getSavePath() {  
      return savePath;  
     }  
  
     public void setSavePath(String savePath) {  
      this.savePath = savePath;  
     }  
  
   
}</span></span>  

struts.xml-------
Xml代码 
<span style="font-size: medium;"><span style="font-size: large;"><?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"   
  
"http://struts.apache.org/dtds/struts-2.1.dtd">  
<struts>  
  <!-- 该属性指定Struts 2文件上传中整个请求内容允许的最大字节数 -->  
<constant name="struts.multipart.maxSize" value="102400000000000" />  
<package name="default" extends="struts-default" >  
   <action name="test" class="com.upload.test.TestAction">  
   <result >/index.jsp</result>  
   </action>  
    
 </package>  
  
</struts>      
</span></span>  


web.xml------
Xml代码 
<span style="font-size: medium;"><span style="font-size: large;"><?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.5"   
    xmlns="http://java.sun.com/xml/ns/javaee"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
    <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>  
  <filter>  
    <filter-name>struts2</filter-name>  
    <filter-class>  
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  
    </filter-class>  
  </filter>  
  <filter-mapping>  
    <filter-name>struts2</filter-name>  
    <url-pattern>/*</url-pattern>  
    </filter-mapping>  
 </web-app>  
</span></span>  

特别说明这条的必要性,可以使你上传任意大小文件
<constant name="struts.multipart.maxSize" value="102400000000000" />

关于FLEX的上传在我博客文章: http://javacrazyer.iteye.com/blog/707693
关于EXT的上传在我博客文章: http://javacrazyer.iteye.com/blog/707510
关于FTP的上传在我的博客文章: http://javacrazyer.iteye.com/blog/675440
关于Struts的上传在我的博客文章: http://javacrazyer.iteye.com/blog/619016[/size]

猜你喜欢

转载自zengxiangshun.iteye.com/blog/1098952