JQuery批量上传插件Uploadify并传参数(二)新版本

来源:互联网 发布:pc蛋蛋牛人算法 编辑:程序博客网 时间:2024/05/05 06:08

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 下载,有问题大家可以一起讨论啊。。。。。

  • uploadify.rar (765.9 KB)
  • 下载次数: 771
  • 查看图片附件

传参数示例:$("#file_upload").uploadify("settings", "formData", {'userName':name,'qq':qq});  

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

0 0
原创粉丝点击