用FileUpload做得文件上传

系统 1676 0
Html代码 复制代码
  1. < form   id = 'myform'   enctype = "multipart/form-data"   action = "<%=webapp %>/UploadFileServlet"   
  2.   method = "post"   target = "hidden_frame" >   
  3. < input   type = "file"   name = "file"   id = "file"   size = "10"   onchange = "this.form.submit();"   />   
  4. < iframe   name = 'hidden_frame'   id = "hidden_frame"   style = 'display:none' > </ iframe >   
  5. </ form >   
    <form id='myform' enctype="multipart/form-data" action="<%=webapp %>/UploadFileServlet"
 method="post" target="hidden_frame">
<input type="file" name="file" id="file" size="10" onchange="this.form.submit();" />
<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
</form>
  

 

webapp是项目的路径名

String webapp=request.getContextPath();

 

后台代码:

 

Java代码 复制代码
  1. import  java.io.File;   
  2. import  java.io.IOException;   
  3. import  java.io.PrintWriter;   
  4. import  java.util.ArrayList;   
  5. import  java.util.HashMap;   
  6. import  java.util.List;   
  7. import  java.util.Map;   
  8.   
  9. import  javax.servlet.ServletException;   
  10. import  javax.servlet.http.HttpServletRequest;   
  11. import  javax.servlet.http.HttpServletResponse;   
  12.   
  13. import  org.apache.commons.fileupload.FileItem;   
  14. import  org.apache.commons.fileupload.disk.DiskFileItemFactory;   
  15. import  org.apache.commons.fileupload.servlet.ServletFileUpload;   
  16. import  org.apache.log4j.Logger;   
  17.   
  18. import  com.siyue.ciap.beans.dic.EnvBean;   
  19. import  com.siyue.ciap.dao.cms.UUIDGenerator;   
  20. import  com.siyue.ciap.dao.phone.ReadFileUtil;   
  21. import  com.siyue.ciap.dao.uitls.ObjectToJSON;   
  22. import  com.siyue.ciap.service.uitl.SpringFacesUtil;   
  23.   
  24.   
  25. public   class  UploadFileServlet  extends  javax.servlet.http.HttpServlet  implements  javax.servlet.Servlet {   
  26.   
  27.      private   static   final  Logger logger = Logger.getLogger(UploadFileServlet. class );   
  28.        
  29.      protected   void  doGet(HttpServletRequest request, HttpServletResponse response)   
  30.              throws  ServletException, IOException {   
  31.          this .doPost(request, response);   
  32.     }   
  33.   
  34.      protected   void  doPost(HttpServletRequest request, HttpServletResponse response)   
  35.              throws  ServletException, IOException {   
  36.         System.out.println( "execute Upload File................." );   
  37.         PrintWriter out = response.getWriter();   
  38.         EnvBean envBean =(EnvBean)SpringFacesUtil   
  39.                .getBean( this .getServletContext(),  "EnvBean" );   
  40.         String uploadPath = envBean.getEnv().getProperty( "upload_dest" ); //上传的路径   
  41.         UUIDGenerator generator= new  UUIDGenerator();   
  42.         DiskFileItemFactory factory =  new  DiskFileItemFactory();   
  43.         factory.setSizeThreshold( 4096 ); //设置缓冲   
  44.         factory.setRepository( new  File(uploadPath)); //设置缓冲区目录   
  45.         ServletFileUpload upload =  new  ServletFileUpload(factory);   
  46.          boolean  isMultipart = ServletFileUpload.isMultipartContent(request);   
  47.         upload.setSizeMax( 1024000000 );   
  48.         List items =  new  ArrayList();   
  49.          try  {   
  50.             items = upload.parseRequest(request);   
  51.             Map rtnMap =  new  HashMap();   
  52.              for ( int  i= 0 ;i<items.size();i++) {   
  53.                 FileItem item = (FileItem) items.get(i);   
  54.                 String autoFileName = generator.generate().toString();   
  55.                  if ( "" .equals(item.getName())) continue ;   
  56.                  //获得文件名   
  57.                 String fileName = item.getName().substring(item.getName()   
  58.                                .lastIndexOf( "\\" )+ 1 , item.getName().length());   
  59.                  //获得文件后缀名   
  60.                 String extName = fileName   
  61.                                .substring(fileName.lastIndexOf( "." )+ 1 , fileName.length());   
  62.                  //判断文件类型   
  63.                  if (!( "xls" .equalsIgnoreCase(extName) ||  "txt" .equalsIgnoreCase(extName) ||    
  64.                          "csv" .equalsIgnoreCase(extName))) {   
  65.                     out.print( "<script>alert('您上传的文件不是excel|txt|csv类型!');</script>" );   
  66.                     out.close();   
  67.                 } else  {   
  68.                     String fileOnlyName = uploadPath + autoFileName +  "."  + extName;   
  69.                     item.write( new  File(fileOnlyName));   
  70.                     Map excelMap =  null ;   
  71.                      if ( "xls" .equalsIgnoreCase(extName)) {   
  72.                         System.out.println( "fileOnlyName------>" +fileOnlyName);   
  73.                         excelMap = ReadFileUtil.readSheetName(fileOnlyName);   
  74.                     }   
  75.                     rtnMap.put( "file" , fileOnlyName);   
  76.                     rtnMap.put( "sheet" , excelMap);   
  77.                     out.print( "<script>parent.callBack(" +ObjectToJSON.MapToJsonStr(rtnMap)+ ")</script>" );   
  78.                     out.close();   
  79.                 }   
  80.             }   
  81.         }  catch  (Exception e) {   
  82.             e.printStackTrace();   
  83.         }   
  84.     }   
  85.        
  86. }  
    import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.siyue.ciap.beans.dic.EnvBean;
import com.siyue.ciap.dao.cms.UUIDGenerator;
import com.siyue.ciap.dao.phone.ReadFileUtil;
import com.siyue.ciap.dao.uitls.ObjectToJSON;
import com.siyue.ciap.service.uitl.SpringFacesUtil;


public class UploadFileServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	private static final Logger logger = Logger.getLogger(UploadFileServlet.class);
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("execute Upload File.................");
		PrintWriter out = response.getWriter();
		EnvBean envBean =(EnvBean)SpringFacesUtil
               .getBean(this.getServletContext(), "EnvBean");
		String uploadPath = envBean.getEnv().getProperty("upload_dest");//上传的路径
		UUIDGenerator generator=new UUIDGenerator();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);//设置缓冲
		factory.setRepository(new File(uploadPath));//设置缓冲区目录
		ServletFileUpload upload = new ServletFileUpload(factory);
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		upload.setSizeMax(1024000000);
		List items = new ArrayList();
		try {
			items = upload.parseRequest(request);
			Map rtnMap = new HashMap();
			for(int i=0;i<items.size();i++) {
				FileItem item = (FileItem) items.get(i);
				String autoFileName = generator.generate().toString();
				if("".equals(item.getName()))continue;
				//获得文件名
				String fileName = item.getName().substring(item.getName()
                               .lastIndexOf("\\")+1, item.getName().length());
				//获得文件后缀名
				String extName = fileName
                               .substring(fileName.lastIndexOf(".")+1, fileName.length());
				//判断文件类型
				if(!("xls".equalsIgnoreCase(extName) || "txt".equalsIgnoreCase(extName) || 
						"csv".equalsIgnoreCase(extName))) {
					out.print("<script>alert('您上传的文件不是excel|txt|csv类型!');</script>");
					out.close();
				}else {
					String fileOnlyName = uploadPath + autoFileName + "." + extName;
					item.write(new File(fileOnlyName));
					Map excelMap = null;
					if("xls".equalsIgnoreCase(extName)) {
						System.out.println("fileOnlyName------>"+fileOnlyName);
						excelMap = ReadFileUtil.readSheetName(fileOnlyName);
					}
					rtnMap.put("file", fileOnlyName);
					rtnMap.put("sheet", excelMap);
					out.print("<script>parent.callBack("+ObjectToJSON.MapToJsonStr(rtnMap)+")</script>");
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
  

 

Java代码 复制代码
  1. EnvBean envBean =(EnvBean)SpringFacesUtil   
  2.                .getBean( this .getServletContext(),  "EnvBean" );   
  3.         String uploadPath = envBean.getEnv().getProperty( "upload_dest" ); //上传的路径   
    EnvBean envBean =(EnvBean)SpringFacesUtil
               .getBean(this.getServletContext(), "EnvBean");
		String uploadPath = envBean.getEnv().getProperty("upload_dest");//上传的路径

  

这句是调Spring找类,根据实际情况变化

Java代码 复制代码
  1. UUIDGenerator generator= new  UUIDGenerator();   
  2. String autoFileName = generator.generate().toString();  
    UUIDGenerator generator=new UUIDGenerator();
String autoFileName = generator.generate().toString();
  

这句是给每个上传的文件加一个唯一标示,可用别的方法替代

Java代码 复制代码
  1. ObjectToJSON这个类是自己写一个Object和Json互转的类  

用FileUpload做得文件上传


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论