jquery插件 jsp+servlet+uploadify3.1 文件上傳

網絡上不少的例子雖說是3.1版本的,可是調用方法都是老版本的,跑不起來,通過查看doc,下面的例子能夠在tomcat中正常運行。 javascript

index.jsp css

[html]  view plain copy print ?
  1. <%@ page language="java" contentType="text/html; charset=utf-8"%>  
  2. <%  
  3.         String path = request.getContextPath();  
  4.         String basePath = request.getScheme() + "://"  
  5.                 + request.getServerName() + ":" + request.getServerPort()  
  6.                 + path + "/";  
  7.     %>      
  8.     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  9.     <html>  
  10.       <head>  
  11.         <base href="<%=basePath%>">  
  12.           
  13.         <title>文件上傳</title>  
  14.           
  15.      <link href="css/uploadify.css" rel="stylesheet" type="text/css" />  
  16.      <script type="text/javascript" src="scripts/jquery-1.7.2.min.js"></script>  
  17.      <script type="text/javascript" src="scripts/jquery.uploadify-3.1.min.js"></script>  
  18.     <script type="text/javascript">  
  19.     $(document).ready(function() {  
  20.      $("#uploadify").uploadify({  
  21.                     'auto'           : false,  
  22.                     'swf'            : '<%=path%>/scripts/uploadify.swf',  
  23.                     'uploader'       : '<%=path%>/scripts/uploadify',//後臺處理的請求  
  24.                     'queueID'        : 'fileQueue',//與下面的id對應  
  25.                     'queueSizeLimit' :1,  
  26.                     'fileTypeDesc'   : 'rar文件或zip文件',  
  27.                     'fileTypeExts'   : '*.rar;*.zip', //控制可上傳文件的擴展名,啓用本項時需同時聲明fileDesc  
  28.                     'multi'          : true,  
  29.                     'buttonText'     : '上傳'  
  30.      });  
  31.     });  
  32.     </script>  
  33.      </head>  
  34.     <body>  
  35.             <div id="fileQueue"></div>  
  36.             <input type="file" name="uploadify" id="uploadify" />  
  37.             <p>  
  38.                 <a href="javascript:$('#uploadify').uploadify('upload')">開始上傳</a>   
  39.                 <a href="javascript:$('#uploadify').uplaodify('cancel','*')">取消上傳</a>  
  40.             </p>  
  41.       </body>  
  42.     </html>  

servlet: Uploadify.java
[java]  view plain copy print ?
  1. package com.rh.core.upload;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.text.SimpleDateFormat;  
  9. import java.util.Date;  
  10. import java.util.Iterator;  
  11. import java.util.List;  
  12.   
  13. import javax.servlet.ServletException;  
  14. import javax.servlet.http.HttpServlet;  
  15. import javax.servlet.http.HttpServletRequest;  
  16. import javax.servlet.http.HttpServletResponse;  
  17.   
  18. import org.apache.commons.fileupload.disk.DiskFileItem;  
  19. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  20. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  21. import org.apache.commons.fileupload.util.Streams;  
  22.   
  23. public class Uploadify extends HttpServlet{  
  24.     private static final long serialVersionUID = 1L;    
  25.         
  26.     /**  
  27.      * 實現多文件的同時上傳  
  28.      */     
  29.     public void doGet(HttpServletRequest request,    
  30.             HttpServletResponse response) throws ServletException, IOException {    
  31.             
  32.         //設置接收的編碼格式    
  33.         request.setCharacterEncoding("UTF-8");    
  34.         Date date = new Date();//獲取當前時間    
  35.         SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmss");    
  36.         SimpleDateFormat sdfFolder = new SimpleDateFormat("yyMM");    
  37.         String newfileName = sdfFileName.format(date);//文件名稱    
  38.         String fileRealPath = "";//文件存放真實地址    
  39.             
  40.         String fileRealResistPath = "";//文件存放真實相對路徑    
  41.             
  42.         //名稱  界面編碼 必須 和request 保存一致..不然亂碼    
  43.         String name = request.getParameter("name");    
  44.                 
  45.              
  46.         String firstFileName="";    
  47.         // 得到容器中上傳文件夾所在的物理路徑    
  48.         String savePath = this.getServletConfig().getServletContext().getRealPath("/") + "uploads\\" + newfileName +"\\";    
  49.         System.out.println("路徑" + savePath+"; name:"+name);    
  50.         File file = new File(savePath);    
  51.         if (!file.isDirectory()) {    
  52.             file.mkdirs();    
  53.         }    
  54.     
  55.         try {    
  56.             DiskFileItemFactory fac = new DiskFileItemFactory();    
  57.             ServletFileUpload upload = new ServletFileUpload(fac);    
  58.             upload.setHeaderEncoding("UTF-8");    
  59.             // 獲取多個上傳文件    
  60.             List fileList = fileList = upload.parseRequest(request);    
  61.             // 遍歷上傳文件寫入磁盤    
  62.             Iterator it = fileList.iterator();    
  63.             while (it.hasNext()) {    
  64.                 Object obit = it.next();  
  65.                 if(obit instanceof DiskFileItem){  
  66.                     System.out.println("xxxxxxxxxxxxx");  
  67.                     DiskFileItem item = (DiskFileItem) obit;    
  68.                         
  69.                     // 若是item是文件上傳表單域       
  70.                     // 得到文件名及路徑       
  71.                     String fileName = item.getName();    
  72.                     if (fileName != null) {    
  73.                         firstFileName=item.getName().substring(item.getName().lastIndexOf("\\")+1);    
  74.                         String formatName = firstFileName.substring(firstFileName.lastIndexOf("."));//獲取文件後綴名    
  75.                         fileRealPath = savePath + newfileName+ formatName;//文件存放真實地址    
  76.                             
  77.                         BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 得到文件輸入流    
  78.                         BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(fileRealPath)));// 得到文件輸出流    
  79.                         Streams.copy(in, outStream, true);// 開始把文件寫到你指定的上傳文件夾    
  80.                         //上傳成功,則插入數據庫    
  81.                         if (new File(fileRealPath).exists()) {    
  82.                             //虛擬路徑賦值    
  83.                             fileRealResistPath=sdfFolder.format(date)+"/"+fileRealPath.substring(fileRealPath.lastIndexOf("\\")+1);    
  84.                             //保存到數據庫    
  85.                             System.out.println("保存到數據庫:");    
  86.                             System.out.println("name:"+name);    
  87.                             System.out.println("虛擬路徑:"+fileRealResistPath);    
  88.                         }    
  89.                              
  90.                     }     
  91.                 }  
  92.             }     
  93.         } catch (org.apache.commons.fileupload.FileUploadException ex) {  
  94.            ex.printStackTrace();    
  95.            System.out.println("沒有上傳文件");    
  96.            return;    
  97.         }     
  98.        response.getWriter().write("1");    
  99.             
  100.     }    
  101.      
  102.     public void doPost(HttpServletRequest req, HttpServletResponse resp)    
  103.             throws ServletException, IOException {    
  104.         doGet(req, resp);    
  105.     }    
  106. }  

web.xml
[html]  view plain copy print ?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app id="WebApp_ID" 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>Uploadify</servlet-name>    
  10.      <servlet-class>com.rh.core.upload.Uploadify</servlet-class>    
  11.     </servlet>    
  12.     <servlet-mapping>    
  13.      <servlet-name>Uploadify</servlet-name>    
  14.      <url-pattern>/scripts/uploadify</url-pattern>    
  15.     </servlet-mapping>  
  16.     <welcome-file-list>  
  17.         <welcome-file>index.jsp</welcome-file>  
  18.     </welcome-file-list>  
  19. </web-app>  

項目截圖:(可能須要修改css文件中圖片的位置)

相關文章
相關標籤/搜索