Java上传各种方式总结

写的很不错,忍不住把人家的文章转载过来,分享给大家

到目前为止:我接触到的有关上传的类型有这么几种
JSP+Servlet的,Struts2的,Struts的,FTP的,ExtJs的,Flex的

最终还是建议看看,后面详细写的Struts2的上传文章最为实用

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

JSP页面具体代码

Html代码 复制代码 收藏代码
  1. <span style="font-size: medium;"><span style="font-size: large;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
  2. <html> 
  3.   <head> 
  4.     <title>JSP+Servlet上传示例</title> 
  5.     <meta http-equiv="pragma" content="no-cache"> 
  6.     <meta http-equiv="cache-control" content="no-cache"> 
  7.     <meta http-equiv="expires" content="0">     
  8.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
  9.     <meta http-equiv="description" content="This is my page"> 
  10.   </head> 
  11.   <body> 
  12.        <form action="upload.do" method="post" enctype="multipart/form-data"> 
  13.       <input type ="file" name="file1" id="file1" /><br/> 
  14.       <input type ="file" name="file2" if="file2"/><br/> 
  15.       <input type ="file" name="file3" id="file3"/><br/> 
  16.        <input type="submit" value="上传" />  
  17.        </form> 
  18.   </body> 
  19. </html></span></span> 
<%@ 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>

上 面文件中有几个需要注意的地方就是
1. action="UploadServlet" 必须和后面的web.xml配置文件中对servlet映射必须保持一致.
2. method="POST" 这里必须为"POST"方式提交不能是"GET".
3. enctype="multipart/form-data" 这里是要提交的内容格式,表示你要提交的是数据流,而不是普通的表单

文本.
4. file1,file2,file3表示你要3个文件一起上传,你也可以一次只上传一个文件.

Servlet处理类程序

Java代码 复制代码 收藏代码
  1. <span style="font-size: medium;"><span style="font-size: large;">package com.upload.test; 
  2. import java.io.BufferedInputStream; 
  3. import java.io.BufferedOutputStream; 
  4. import java.io.File; 
  5. import java.io.FileOutputStream; 
  6. import java.io.IOException; 
  7. import javax.servlet.ServletException; 
  8. import javax.servlet.http.HttpServlet; 
  9. import javax.servlet.http.HttpServletRequest; 
  10. import javax.servlet.http.HttpServletResponse; 
  11. import org.apache.commons.fileupload.FileItemIterator; 
  12. import org.apache.commons.fileupload.FileItemStream; 
  13. import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
  14. import org.apache.commons.fileupload.servlet.ServletFileUpload; 
  15. import org.apache.commons.fileupload.util.Streams; 
  16.  
  17. public class UploadServlet extends HttpServlet { 
  18.      
  19.     File tmpDir = null;//初始化上传文件的临时存放目录 
  20.     File saveDir = null;//初始化上传文件后的保存目录 
  21.     public void doGet(HttpServletRequest request, HttpServletResponse response) 
  22.             throws ServletException, IOException { 
  23.         this.doPost(request, response); 
  24.     } 
  25.     public void doPost(HttpServletRequest request, HttpServletResponse response) 
  26.             throws ServletException, IOException { 
  27.         request.setCharacterEncoding("utf-8"); 
  28.         try
  29.             if(ServletFileUpload.isMultipartContent(request)){ 
  30.             DiskFileItemFactory dff = new DiskFileItemFactory();//创建该对象 
  31.             dff.setRepository(tmpDir);// 指定上传文件的临时目录 
  32.             dff.setSizeThreshold(1024000);//指定在内存中缓存数据大小,单位为byte 
  33.             ServletFileUpload sfu = new ServletFileUpload(dff);//创建该对象 
  34.             sfu.setFileSizeMax(5000000);// 指定单个上传文件的最大尺寸 
  35.             sfu.setSizeMax(10000000);//指定一次上传多个文件的 总尺寸 
  36.             FileItemIterator fii = sfu.getItemIterator(request);//解析request 请求, 
  37.  
  38. 并返回FileItemIterator集合 
  39.             while(fii.hasNext()){ 
  40.             FileItemStream fis = fii.next();//从集合中获得一个文件流 
  41.             if(!fis.isFormField() && fis.getName().length()>0){//过滤掉表单中非文件 
  42.  
  43. 域 
  44.             String fileName = fis.getName().substring(fis.getName().lastIndexOf 
  45.  
  46. ("\\"));//获得上传文件的文件名 
  47.             BufferedInputStream in = new BufferedInputStream(fis.openStream());//获 
  48.  
  49. 得文件输入流 
  50.             BufferedOutputStream out = new BufferedOutputStream(new  
  51.  
  52. FileOutputStream(new File(saveDir+fileName)));//获得文件输出流 
  53.             Streams.copy(in, out, true);//开始把文件写到你指定的上传文件夹 
  54.             } 
  55.             } 
  56.             response.getWriter().println("File upload successfully!!!");//终于成功了 
  57.  
  58. ,还不到你的上传文件中看看,你要的东西都到齐了吗 
  59.             } 
  60.             }catch(Exception e){ 
  61.             e.printStackTrace(); 
  62.             } 
  63.     } 
  64.     @Override 
  65.     public void init() throws ServletException { 
  66.         super.init(); 
  67.         /* 对上传文件夹和临时文件夹进行初始化
  68.         *
  69.         */ 
  70.         String tmpPath = "c:\\tmpdir"
  71.         String savePath = "c:\\updir"
  72.         tmpDir = new File(tmpPath); 
  73.         saveDir = new File(savePath); 
  74.         if(!tmpDir.isDirectory()) 
  75.         tmpDir.mkdir(); 
  76.         if(!saveDir.isDirectory()) 
  77.         saveDir.mkdir(); 
  78.  
  79.     } 
  80.      
  81. }</span></span> 
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();

	}
	
}

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

Html代码 复制代码 收藏代码
  1. <span style="font-size: medium;"><span style="font-size: large;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
  2. <%@ taglib uri="/struts-tags" prefix="s"%> 
  3. <
  4. String path = request.getContextPath(); 
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() 
  6.  
  7. +path+"/"; 
  8. %> 
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
  10. <html> 
  11.   <head> 
  12.   </head>   
  13. <body> 
  14. <s:form action="test.action" method="POST" enctype="multipart/form-data"> 
  15. <s:file label="选择文件" name="upFile"></s:file> 
  16. <s:submit label="上传" /> 
  17. </s:form> 
  18. </body> 
  19. </html> 
  20. </span></span> 
<%@ 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>

UploadAction----------------

Java代码 复制代码 收藏代码
  1. <span style="font-size: medium;"><span style="font-size: large;">package com.upload.test; 
  2.  
  3. import java.io.BufferedInputStream; 
  4. import java.io.BufferedOutputStream; 
  5. import java.io.File; 
  6. import java.io.FileInputStream; 
  7. import java.io.FileOutputStream; 
  8.  
  9. import com.opensymphony.xwork2.ActionSupport; 
  10.  
  11. public class UploadAction extends ActionSupport { 
  12.     private File   upFile; 
  13.      private String upFileFileName;  //上传的文件名 (1.系统自动注入  2.变量命名有规则: 前台 
  14.  
  15. 对象名+"FileName"
  16.      private String upFileContentType; //文件类型           (1.系统自动注入  2.变量命名有规 
  17.  
  18. 则: 前台对象名+"ContentType"
  19.      private String savePath; 
  20.       
  21.       
  22.      @Override 
  23.      public String execute() throws Exception { 
  24.       System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxx"); 
  25.       String path = "c:/" + upFileFileName; 
  26.       BufferedInputStream bis = null
  27.       BufferedOutputStream bos = null
  28.        
  29.       try
  30.        bis = new BufferedInputStream(new FileInputStream(upFile)); 
  31.        bos = new BufferedOutputStream(new FileOutputStream(path)); 
  32.        byte[] buf = new byte[(int)upFile.length()]; 
  33.        int len = 0
  34.        while(((len=bis.read(buf))!=-1)){ 
  35.         bos.write(buf, 0, len); 
  36.        } 
  37.       }catch(Exception e){ 
  38.        e.printStackTrace(); 
  39.       }finally
  40.         try
  41.           if(bos!=null){ 
  42.            bos.close(); 
  43.           } 
  44.           if(bis!=null){ 
  45.            bis.close(); 
  46.           } 
  47.         }catch(Exception e){ 
  48.        bos = null
  49.        bis = null
  50.         } 
  51.       } 
  52.              
  53.       return SUCCESS; 
  54.      } 
  55.  
  56.       
  57.      public File getUpFile() { 
  58.       return upFile; 
  59.      } 
  60.  
  61.      public void setUpFile(File upFile) { 
  62.       this.upFile = upFile; 
  63.      } 
  64.  
  65.      public String getUpFileFileName() { 
  66.       return upFileFileName; 
  67.      } 
  68.  
  69.      public void setUpFileFileName(String upFileFileName) { 
  70.       this.upFileFileName = upFileFileName; 
  71.      } 
  72.  
  73.      public String getUpFileContentType() { 
  74.       return upFileContentType; 
  75.      } 
  76.  
  77.      public void setUpFileContentType(String upFileContentType) { 
  78.       this.upFileContentType = upFileContentType; 
  79.      } 
  80.  
  81.      public String getSavePath() { 
  82.       return savePath; 
  83.      } 
  84.  
  85.      public void setSavePath(String savePath) { 
  86.       this.savePath = savePath; 
  87.      } 
  88.  
  89.   
  90. }</span></span> 
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;
	 }

 
}

struts.xml-------

Xml代码 复制代码 收藏代码
  1. <span style="font-size: medium;"><span style="font-size: large;"><?xml version="1.0" encoding="UTF-8" ?> 
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"  
  3.  
  4. "http://struts.apache.org/dtds/struts-2.1.dtd"> 
  5. <struts> 
  6.   <!-- 该属性指定Struts 2文件上传中整个请求内容允许的最大字节数 --> 
  7. <constant name="struts.multipart.maxSize" value="102400000000000" /> 
  8. <package name="default" extends="struts-default" > 
  9.    <action name="test" class="com.upload.test.TestAction"> 
  10.    <result >/index.jsp</result> 
  11.    </action> 
  12.    
  13. </package> 
  14.  
  15. </struts>     
  16. </span></span> 
<?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>    

web.xml------

Xml代码 复制代码 收藏代码
  1. <span style="font-size: medium;"><span style="font-size: large;"><?xml version="1.0" encoding="UTF-8"?> 
  2. <web-app version="2.5"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
  7.     <welcome-file>index.jsp</welcome-file> 
  8.   </welcome-file-list> 
  9.   <filter> 
  10.     <filter-name>struts2</filter-name> 
  11.     <filter-class> 
  12.         org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter 
  13.     </filter-class> 
  14.   </filter> 
  15.   <filter-mapping> 
  16.     <filter-name>struts2</filter-name> 
  17.     <url-pattern>/*</url-pattern> 
  18.     </filter-mapping> 
  19. </web-app> 
  20. </span></span> 
<?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>

特别说明这条的必要性,可以使你上传任意大小文件
<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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值