JQuery批量上傳插件Uploadify並傳參數(二)新版本

Uploadify是一個Jquery框架下處理批量文件上傳的插件,支持多種服務器端軟件。

 

官網:http://www.uploadify.com/

文檔:http://www.uploadify.com/documentation/

 

今天根據文檔寫了個批量上傳的的功能..

 

下面直接進入主題:

 

界面效果:

 



 

 界面代碼:

 

Html代碼  收藏代碼
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>  
  2. <%  
  3.     String path = request.getContextPath();  
  4. %>  
  5.   
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  7. <html>  
  8.     <head>  
  9.   
  10.         <title>Uploadify上傳</title>  
  11.         <meta http-equiv="pragma" content="no-cache">  
  12.         <meta http-equiv="cache-control" content="no-cache">  
  13.         <meta http-equiv="expires" content="0">  
  14.         <link rel="stylesheet" href="uploadify/uploadify.css" type="text/css"></link>  
  15.         <script type="text/javascript" src="uploadify/jquery-1.7.2.min.js"></script>  
  16.         <script type="text/javascript"  
  17.             src="uploadify/jquery.uploadify-3.1.min.js"></script>  
  18.         <script type="text/javascript">  
  19.                 
  20.             $(function() {  
  21.                 $("#file_upload").uploadify({  
  22.                     'height'        : 27,   
  23.                     'width'         : 80,    
  24.                     'buttonText'    : '瀏 覽',  
  25.                     'swf'           : '<%=path%>/uploadify/uploadify.swf',  
  26.                     'uploader'      : '<%=path%>/servlet/UploadifySerlet',  
  27.                     'auto'          : false,  
  28.                     'fileTypeExts'  : '*.xls',  
  29.                     'formData'      : {'userName':'','qq':''},  
  30.                     'onUploadStart' : function(file) {  
  31.                            
  32.                         //校驗     
  33.                         var name=$('#userName').val();      
  34.                          if(name.replace(/\s/g,'') == ''){     
  35.                               alert("名稱不能爲空!");     
  36.                               return false;     
  37.                          }   
  38.                            
  39.                          //校驗     
  40.                         var qq=$('#qq').val();      
  41.                          if(qq.replace(/\s/g,'') == ''){     
  42.                               alert("QQ不能爲空!");     
  43.                               return false;     
  44.                          }  
  45.                            
  46.                         $("#file_upload").uploadify("settings", "formData", {'userName':name,'qq':qq});  
  47.                         //$("#file_upload").uploadify("settings", "qq", );  
  48.                     }  
  49.                 });  
  50.             });  
  51.           
  52.     </script>  
  53.     </head>  
  54.   
  55.     <body>  
  56.   
  57.         名稱: <input type="text" id="userName" name="userName" value="妞見妞愛">  
  58.         <br>  
  59.          QQ: <input type="text" id="qq" name="qq" value="609865047">  
  60.         <br>  
  61.         <input type="file" name="uploadify" id="file_upload" />  
  62.         <hr>  
  63.         <a href="javascript:$('#file_upload').uploadify('upload','*')">開始上傳</a>&nbsp;     
  64.         <a href="javascript:$('#file_upload').uploadify('cancel', '*')">取消所有上傳</a>   
  65.     </body>  
  66. </html>  

 

  關於各個參數的介紹,網上也有很多。。我們也可以在 jquery.uploadify-3.1.js 中找到。

 

Js代碼  收藏代碼
  1. var settings = $.extend({  
  2.                     // Required Settings  
  3.                     id       : $this.attr('id'), // The ID of the DOM object  
  4.                     swf      : 'uploadify.swf',  // The path to the uploadify SWF file  
  5.                     uploader : 'uploadify.php',  // The path to the server-side upload script  
  6.                       
  7.                     // Options  
  8.                     auto            : true,               // Automatically upload files when added to the queue  
  9.                     buttonClass     : '',                 // A class name to add to the browse button DOM object  
  10.                     buttonCursor    : 'hand',             // The cursor to use with the browse button  
  11.                     buttonImage     : null,               // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button  
  12.                     buttonText      : 'SELECT FILES',     // The text to use for the browse button  
  13.                     checkExisting   : false,              // The path to a server-side script that checks for existing files on the server  
  14.                     debug           : false,              // Turn on swfUpload debugging mode  
  15.                     fileObjName     : 'Filedata',         // The name of the file object to use in your server-side script  
  16.                     fileSizeLimit   : 0,                  // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit)  
  17.                     fileTypeDesc    : 'All Files',        // The description for file types in the browse dialog  
  18.                     fileTypeExts    : '*.*',              // Allowed extensions in the browse dialog (server-side validation should also be used)  
  19.                     height          : 30,                 // The height of the browse button  
  20.                     method          : 'post',             // The method to use when sending files to the server-side upload script  
  21.                     multi           : true,               // Allow multiple file selection in the browse dialog  
  22.                     formData        : {},                 // An object with additional data to send to the server-side upload script with every file upload  
  23.                     preventCaching  : true,               // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)  
  24.                     progressData    : 'percentage',       // ('percentage' or 'speed') Data to show in the queue item during a file upload  
  25.                     queueID         : false,              // The ID of the DOM object to use as a file queue (without the #)  
  26.                     queueSizeLimit  : 999,                // The maximum number of files that can be in the queue at one time  
  27.                     removeCompleted : true,               // Remove queue items from the queue when they are done uploading  
  28.                     removeTimeout   : 3,                  // The delay in seconds before removing a queue item if removeCompleted is set to true  
  29.                     requeueErrors   : false,              // Keep errored files in the queue and keep trying to upload them  
  30.                     successTimeout  : 30,                 // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading  
  31.                     uploadLimit     : 0,                  // The maximum number of files you can upload  
  32.                     width           : 120,                // The width of the browse button  
  33.                       

 

 上面是默認的設置。。。

 

  服務器端代碼:

 

Java代碼  收藏代碼
  1. package com.yangpan.uploadify;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.io.PrintWriter;  
  9. import java.text.SimpleDateFormat;  
  10. import java.util.Arrays;  
  11. import java.util.Date;  
  12. import java.util.Iterator;  
  13. import java.util.List;  
  14. import java.util.Random;  
  15.   
  16. import javax.servlet.ServletException;  
  17. import javax.servlet.http.HttpServlet;  
  18. import javax.servlet.http.HttpServletRequest;  
  19. import javax.servlet.http.HttpServletResponse;  
  20.   
  21. import org.apache.commons.fileupload.FileItem;  
  22. import org.apache.commons.fileupload.FileUploadException;  
  23. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  24. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  25.   
  26. public class UploadifySerlet extends HttpServlet {  
  27.   
  28.     /** 
  29.      *  
  30.      */  
  31.     private static final long serialVersionUID = 1L;  
  32.   
  33.     //上傳文件的保存路徑  
  34.     protected String configPath = "attached/";  
  35.   
  36.     protected String dirTemp = "attached/temp/";  
  37.       
  38.     protected String dirName = "file";  
  39.       
  40.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  41.             throws ServletException, IOException {  
  42.          this.doPost(request, response);  
  43.     }  
  44.   
  45.        
  46.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  47.             throws ServletException, IOException {  
  48.           
  49.         request.setCharacterEncoding("UTF-8");  
  50.         response.setContentType("text/html; charset=UTF-8");  
  51.         PrintWriter out = response.getWriter();  
  52.           
  53.         //文件保存目錄路徑  
  54.         String savePath = this.getServletContext().getRealPath("/") + configPath;  
  55.           
  56.         // 臨時文件目錄   
  57.         String tempPath = this.getServletContext().getRealPath("/") + dirTemp;  
  58.           
  59.         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");  
  60.         String ymd = sdf.format(new Date());  
  61.         savePath += "/" + ymd + "/";  
  62.         //創建文件夾  
  63.         File dirFile = new File(savePath);  
  64.         if (!dirFile.exists()) {  
  65.             dirFile.mkdirs();  
  66.         }  
  67.           
  68.         tempPath += "/" + ymd + "/";  
  69.         //創建臨時文件夾  
  70.         File dirTempFile = new File(tempPath);  
  71.         if (!dirTempFile.exists()) {  
  72.             dirTempFile.mkdirs();  
  73.         }  
  74.           
  75.         DiskFileItemFactory  factory = new DiskFileItemFactory();  
  76.         factory.setSizeThreshold(20 * 1024 * 1024); //設定使用內存超過5M時,將產生臨時文件並存儲於臨時目錄中。     
  77.         factory.setRepository(new File(tempPath)); //設定存儲臨時文件的目錄。     
  78.   
  79.         ServletFileUpload upload = new ServletFileUpload(factory);  
  80.         upload.setHeaderEncoding("UTF-8");  
  81.           
  82.           
  83.            
  84.         try {  
  85.             List items = upload.parseRequest(request);  
  86.             Iterator itr = items.iterator();  
  87.               
  88.             String name = "";  
  89.             String qq = "";  
  90.               
  91.             while (itr.hasNext()) {  
  92.                 FileItem item = (FileItem) itr.next();  
  93.                 String fileName = item.getName();  
  94.                 long fileSize = item.getSize();  
  95.                 if (!item.isFormField()) {  
  96.                     String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();  
  97.                       
  98.                     SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
  99.                     String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;  
  100.                     try{  
  101.                         File uploadedFile = new File(savePath, newFileName);  
  102.                           
  103.                         /* 
  104.                          * 第一種方法 
  105.                          *  
  106.                          * 好處: 一目瞭然..簡單啊... 
  107.                          * 弊端: 這種方法會導致上傳的文件大小比原來的文件要大 
  108.                          *  
  109.                          * 推薦使用第二種 
  110.                          */  
  111.                         //item.write(uploadedFile);  
  112.                         //--------------------------------------------------------------------  
  113.                         //第二種方法  
  114.                         OutputStream os = new FileOutputStream(uploadedFile);  
  115.                         InputStream is = item.getInputStream();  
  116.                         byte buf[] = new byte[1024];//可以修改 1024 以提高讀取速度  
  117.                         int length = 0;    
  118.                         while( (length = is.read(buf)) > 0 ){    
  119.                             os.write(buf, 0, length);    
  120.                         }    
  121.                         //關閉流    
  122.                         os.flush();  
  123.                         os.close();    
  124.                         is.close();    
  125.                         System.out.println("上傳成功!路徑:"+savePath+"/"+newFileName);  
  126.                         out.print("1");  
  127.                     }catch(Exception e){  
  128.                         e.printStackTrace();  
  129.                     }  
  130.                 }else {  
  131.                     String filedName = item.getFieldName();  
  132.                     if (filedName.equals("userName")) {  
  133.                         name = item.getString();  
  134.                     }else {  
  135.                         qq = item.getString();  
  136.                     }  
  137.                     System.out.println("FieldName:"+filedName);  
  138.                     System.out.println("String:"+item.getString("UTF-8"));//避免中文亂碼  
  139.                     //System.out.println("String():"+item.getString(item.getName()));  
  140.                     System.out.println("===============");   
  141.                 }             
  142.             }   
  143.               
  144.         } catch (FileUploadException e) {  
  145.             // TODO Auto-generated catch block  
  146.             e.printStackTrace();  
  147.         }  
  148.         out.flush();  
  149.         out.close();  
  150.     }  
  151.   
  152. }  

 

 

  WEB.XML

 

Xml代碼  收藏代碼
  1. <servlet>  
  2.         <servlet-name>UploadifySerlet</servlet-name>  
  3.         <servlet-class>  
  4.             com.yangpan.uploadify.UploadifySerlet  
  5.         </servlet-class>  
  6.     </servlet>  
  7.   
  8.     <servlet-mapping>  
  9.         <servlet-name>UploadifySerlet</servlet-name>  
  10.         <url-pattern>/servlet/UploadifySerlet</url-pattern>  
  11.     </servlet-mapping>  

 

 

 

基本設置

swf:主要Flash文件路徑,默認uploadify.swf,如果同調用文件在同一不目錄下可以忽略

uploader:後臺處理程序路徑,默認uploadify.php

postData:傳遞參數,默認{}

auto:是否允許自動上傳文件,默認false

method:傳遞參數方式,默認post

 

外觀設置

width:按鈕寬度,默認120

height:按鈕高度,默認30

buttonClass:按鈕樣式設置,如:樣式爲.btnClass{color:red;}

buttonCursor:鼠標移入時指針樣式,默認hand,(注:設置後不知道怎麼顯示)

buttonImage:按鈕顯示圖片地址,默認false,(注:必須是高度2倍,包含兩個按鈕圖片,上默認、下鼠標移入,IE9)

buttonText:按鈕顯示文字信息,默認SELECT FILES,(注:3.0.0版本支持中文)

cancelImage:取消選中文件圖片,默認uploadify-cancel.png

fileTypeDesc:選擇文件時文件類型提示,默認All Files (*.*)

fileTypeExts:選擇文件時文件類型限制,默認*.*,(注:如果fileTypeDesc和fileTypeExts同時設置,則顯示組合,如:All Files (*.*) (*.*)

多個類型如:“*.JPG;*.GIF;*.PNG;*.BMP”)

 

操作設置

queueID:上傳隊列容器ID,默認false

removeCompleted:是否刪除容器內已經上傳完畢文件,默認true

removeTimeout:刪除容器內已經上傳完畢文件延遲時間,單位s,默認3

fileSizeLimit:設置允許上傳文件大小,單位k,默認0不限制

multi:是否支持多文件同時上傳,默認false

queueSizeLimit:限制一次上傳文件個數,即容器內最多文件個數,默認999

simUploadLimit:允許同時上傳文件個數,同時執行,默認1,(注:3.0.0測試版註釋此參數)

調試設置

debug:是否顯示調試框,默認false

checkExisting:檢查待上傳文件是否存在程序,默認uploadify-check-existing.php

其他設置

fileObjName:設置一個名字,在服務器處理程序中根據該名字來取上傳文件的數據,默認Filedata,(作用不明)

requeueErrors:未知,默認false

preventCaching:未知,默認true

progressData:未知,默認percentage

successTimeout:未知,默認30

transparent:未知,默認true

uploadLimit:未知,默認999

uploaderType:未知,默認html5

langFile:錯誤提示文件,可以忽略

id:當前操作的ID編碼,默認jQuery(this).attr('id'),可以忽略。

 

onClearQueue: function () {}:未知

onDialogOpen: function () {}:打開選擇文件窗口

onDialogClose: function () {}:關閉選擇文件窗口

onInit: function () {}:初始化

onQueueComplete: function () {}:全部文件上傳結束

onSelectError: function () {}:選擇文件:選擇錯誤

onSelect: function () {}:單個文件:選擇文件,每選中一個文件都執行一次

onSWFReady: function () {}:未知

onUploadCancel: function () {}:未知

onUploadComplete: function () {}:單個文件上傳結束,注意:最後一個文件結束在全部結束後

onUploadError: function () {}:上傳文件錯誤/取消已選擇文件

onUploadProgress: function () {}:單個文件:上傳過程中

 

demo 下載,有問題大家可以一起討論啊。。。。。

傳參數示例:$("#file_upload").uploadify("settings", "formData", {'userName':name,'qq':qq});  

源地址:http://yangpanwww.iteye.com/blog/1550508

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章