zoukankan      html  css  js  c++  java
  • JQuery上传插件uploadify优化

    旧版的uploadify是基于flash上传的,但是总有那么些问题,让我们用的不是很舒服。今天主要分享下在项目中用uploadify遇到的一些问题,以及优化处理

    官方下载

    官方文档

    官方演示

    下面是官方下载包含的一些文件,当然很多我们在项目中是不需要的

    效果图:

    下面贴代码:

     1 document.write('<link href="/js/uploadify/uploadify.css" rel="stylesheet" type="text/css" />');
     2 document.write('<script src="/js/uploadify/jquery.uploadify.js" type="text/javascript"></script>');
     3 (function ($) {
     4     $.fn.uploadDOC = function (callback, guid, url, queueID,removeCompleted) {
     5         /// <summary>
     6         ///     基于jQuery上传插件uploadify封装。
     7         /// </summary>
     8         /// <param name="callback" type="function">
     9         ///     上传成功时执行的回调函数。
    10         /// </param>
    11         /// <param name="guid" type="String">
    12         ///     传入产生的随机guid。
    13         /// </param>
    14         /// <param name="url" type="String">
    15         ///     传入地址。
    16         /// </param>
    17         /// <param name="queueID" type="String">
    18         ///     上传队列展示的div或span对应的id。
    19         /// </param>
    20         /// <param name="removeCompleted" type="Boolean">
    21         ///     移除已上传成功的队列。Ture:执行移除;False:保留队列。
    22         /// </param>
    23         $(this).uploadify({
    24             'auto': true,
    25             'buttonImage': '/images/bjdz_btn_xzwj.gif',
    26             'buttonText': '点击上传',
    27             'fileSizeLimit': '5MB',
    28             'fileTypeDesc': '请选择Word文件',
    29             'fileTypeExts': '*.doc;*.docx',
    30             'height': 27,
    31             'method': 'post',
    32             'multi': false,
    33             'queueID': queueID == undefined ? "some" : queueID,
    34             'queueSizeLimit': 1,
    35             'removeCompleted': removeCompleted,
    36             'swf': '/js/uploadify/uploadify.swf',
    37             'uploader': url == undefined ? 'http://imgupload.kuaiyoudai.com/user/uploadcommon.ashx?para=' + guid : url,
    38             'width': 76,
    39             'overrideEvents': ['onUploadSuccess'],
    40             'onUploadSuccess': function onUploadSuccess(file, data, response) {
    41                                     if (typeof callback === "function") {
    42                                         if (response) {
    43                                             callback(data);
    44                                         }
    45                                     }
    46                                 }
    47         });
    48     }
    49 
    50     $.fn.upload = function (callback, guid, url, queueID, removeCompleted) {
    51         /// <summary>
    52         ///     基于jQuery上传插件uploadify封装。
    53         /// </summary>
    54         /// <param name="callback" type="function">
    55         ///     上传成功时执行的回调函数。
    56         /// </param>
    57         /// <param name="guid" type="String">
    58         ///     传入产生的随机guid。
    59         /// </param>
    60         /// <param name="url" type="String">
    61         ///     传入地址。
    62         /// </param>
    63         /// <param name="queueID" type="String">
    64         ///     上传队列展示的div或span对应的id。
    65         /// </param>
    66         /// <param name="removeCompleted" type="Boolean">
    67         ///     移除已上传成功的队列。Ture:执行移除;False:保留队列。
    68         /// </param>
    69         $(this).uploadify({
    70             'auto': true,
    71             'buttonImage': '/images/bjdz_btn_xzwj.gif',
    72             'buttonText': '点击上传',
    73             'fileSizeLimit': '5MB',
    74             'fileTypeDesc': '请选择图片文件',
    75             'fileTypeExts': '*.jpg;*.jpeg;*.gif;*.png;',
    76             'height': 27,
    77             'method': 'post',
    78             'multi': false,
    79             'queueID': queueID == undefined ? "some" : queueID,
    80             'queueSizeLimit': 1,
    81             'removeCompleted': removeCompleted,
    82             'swf': '/js/uploadify/uploadify.swf',
    83             'uploader': url == undefined ? 'http://imgupload.kuaiyoudai.com/user/uploadcommon.ashx?para=' + guid : url,
    84             'width': 76,
    85             'overrideEvents': ['onUploadSuccess'],
    86             'onUploadSuccess': function onUploadSuccess(file, data, response) {
    87                                     if (typeof callback === "function") {
    88                                         if (response) {
    89                                             callback(data);
    90                                         }
    91                                     }
    92                                 }
    93         });
    94     }
    95 })($);
    upload.js

    前台代码:

     1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="uploadify_Demo.Demo" %>
     2 
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     4 
     5 <html xmlns="http://www.w3.org/1999/xhtml">
     6 <head runat="server">
     7     <title></title>
     8     <script src="/js/jquery-1.8.3.js" type="text/javascript"></script>
     9     <script src="/js/upload.js" type="text/javascript"></script>
    10     <script type="text/javascript">
    11         $(function () {
    12             $("#btn_Upload").upload(function (data) { alert(data); }, "<%= Guid.NewGuid().ToString() %>");
    13         });
    14     </script>
    15 </head>
    16 <body>
    17     <form id="form1" runat="server">
    18     <div>
    19         <input type="button" name="" value="上传文件" id="btn_Upload" />
    20     </div>
    21     </form>
    22 </body>
    23 </html>
    Demo.html

    下面分享下开发中遇到的问题:

    官方的直接用会有一些问题

    1、多发了一个对于网站根目录的请求

    解决方法:

    在jquery.uploadify.js文件中找到下面这段代码

    this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url)

    替换为

    this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);this.settings.button_image_url = this.settings.button_image_url ? SWFUpload.completeURL(this.settings.button_image_url) : this.settings.button_image_url

    参考自:http://unixlzx.blog.163.com/blog/static/102773752201332505110380/

    2、每次带有上传功能的页面初始化都会对swf文件发三次请求

     这个问题在网上查了几天,去uploadify社区去看了几天老外的各种提问,没找到解决方法,这个对于上传功能是没有任何影响的,但是开着不怎么爽,就自己调试找方法解决,当然皇天不负有心人,找到了问题的根源,有几种解决方法,我给大家分享一个我这次用的。

    对于自己写一个上传插件,不用uploadify也有想过,不过时间上不怎么够,所以就对uploadify进行了简单的处理

    效果图:

    只有一次对于swf文件的请求了,而且对于网站根目录的请求没有了

    原先对与swf文件多发的两次请求的语句分别是

    $('#' + swfuploadify.movieName).wrap($wrapper);

    // Adjust the styles of the movie
    $('#' + swfuploadify.movieName).css({
      'position' : 'absolute',
      'z-index'  : 1
    });

    大家应该找到共同之处了,原因就是调用了 flash 生成的object对象,我的解决方法是避免调用这个对象,所以我在项目中将我的上传按钮  强制必须 要求放到一个div(容器,p标签,span标签都行)中

    官方也就是想把Object对象放入到一个div中进行处理,我也就按他们的意思,只不过反其道而位置

    不多说,贴代码

     1 if (flashInstalled) {
     2     var swfuploadify = new SWFUpload(swfUploadSettings); ;
     3 
     4     // Add the SWFUpload object to the elements data object
     5     $this.data('uploadify', swfuploadify);
     6 
     7     $('#' + swfuploadify.movieName).parent().attr('id', settings.id).addClass('uploadify').css({
     8         'height': settings.height + 'px',
     9         'width': settings.width + 'px'
    10     });
    11 
    12     // Recreate the reference to wrapper
    13     var $wrapper = $('#' + settings.id);
    14     // Add the data object to the wrapper 
    15     $wrapper.data('uploadify', swfuploadify);
    16 
    17     // Create the button
    18     var $button = $('<div />', {
    19         'id': settings.id + '-button',
    20         'class': 'uploadify-button ' + settings.buttonClass
    21     });
    22     if (settings.buttonImage) {
    23         $button.css({
    24             'background-image': "url('" + settings.buttonImage + "')",
    25             'text-indent': '-9999px'
    26         });
    27     }
    28     $button.html('<span class="uploadify-button-text">' + settings.buttonText + '</span>')
    29     .css({
    30         'height': settings.height + 'px',
    31         'line-height': settings.height + 'px',
    32         'width': settings.width + 'px',
    33         'margin-top': '-' + settings.height + 'px'
    34     });
    35     // Append the button to the wrapper
    36     $wrapper.append($button);
    37 
    38     // Create the file queue
    39     if (!settings.queueID) {
    40         var $queue = $('<div />', {
    41             'id': settings.id + '-queue',
    42             'class': 'uploadify-queue'
    43         });
    44         $wrapper.after($queue);
    45         swfuploadify.settings.queueID = settings.id + '-queue';
    46         swfuploadify.settings.defaultQueue = true;
    47     }
    48 
    49     // Create some queue related objects and variables
    50     swfuploadify.queueData = {
    51         files: {}, // The files in the queue
    52         filesSelected: 0, // The number of files selected in the last select operation
    53         filesQueued: 0, // The number of files added to the queue in the last select operation
    54         filesReplaced: 0, // The number of files replaced in the last select operation
    55         filesCancelled: 0, // The number of files that were cancelled instead of replaced
    56         filesErrored: 0, // The number of files that caused error in the last select operation
    57         uploadsSuccessful: 0, // The number of files that were successfully uploaded
    58         uploadsErrored: 0, // The number of files that returned errors during upload
    59         averageSpeed: 0, // The average speed of the uploads in KB
    60         queueLength: 0, // The number of files in the queue
    61         queueSize: 0, // The size in bytes of the entire queue
    62         uploadSize: 0, // The size in bytes of the upload queue
    63         queueBytesUploaded: 0, // The size in bytes that have been uploaded for the current upload queue
    64         uploadQueue: [], // The files currently to be uploaded
    65         errorMsg: '某些文件无法加入到上传队列中:'
    66     };
    67 
    68     // Save references to all the objects
    69     //swfuploadify.original = $clone;
    70     //swfuploadify.wrapper = $wrapper;
    71     //swfuploadify.button = $button;
    72     swfuploadify.queue = $queue;
    73 
    74     // Call the user-defined init event handler
    75     if (settings.onInit) settings.onInit.call($this, swfuploadify);
    76 
    77 } else {
    78 
    79     // Call the fallback function
    80     if (settings.onFallback) settings.onFallback.call($this);
    81 
    82 }

    代码从flash加载成功开始

    最后我修改后的uploadify.js文件去除了一些英文提示,加入国人都能看懂的中文提示。

    还修改了修正了一处Bug

    // Triggered when a file is not added to the queue
    onSelectError : function(file, errorCode, errorMsg) {
        // Load the swfupload settings
        var settings = this.settings;
    
        // Run the default event handler
        if ($.inArray('onSelectError', settings.overrideEvents) < 0) {
            switch(errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    if (settings.queueSizeLimit > errorMsg) {
                        this.queueData.errorMsg += '
    The number of files selected exceeds the remaining upload limit (' + errorMsg + ').';
                    } else {
                        this.queueData.errorMsg += '
    The number of files selected exceeds the queue size limit (' + settings.queueSizeLimit + ').';
                    }
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    this.queueData.errorMsg += '
    The file "' + file.name + '" exceeds the size limit (' + settings.fileSizeLimit + ').';
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    this.queueData.errorMsg += '
    The file "' + file.name + '" is empty.';
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:      //这边bug  SWFUpload.QUEUE_ERROR.INVALID_FILETYPE
                    this.queueData.errorMsg += '
    The file "' + file.name + '" is not an accepted file type (' + settings.fileTypeDesc + ').';
                    break;
            }
        }
        if (errorCode != SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
            delete this.queueData.files[file.id];
        }
    
        // Call the user-defined event handler
        if (settings.onSelectError) settings.onSelectError.apply(this, arguments);
    },

    官方的第四个selectError判断重复了,将其修改为case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:

    下面贴个项目的下载地址,虽然很简单,但是免去大家重写js的痛苦

    uploadify_Demo

     

    本文版权归作者和博客园共有,来源网址:http://www.cnblogs.com/tq1226112215/
    欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Golang 用go-sql-driver 调用MySQL存储过程时的问题排查
    mysqlbinlog 查看binlog时报错unknown variable 'default-character-set=utf8'
    HBase Go客户端Row构造注意事项
    MySQL JOIN操作报错问题小解
    MySQL主从同步的一个小问题解决
    PHP 多个mysql连接的问题
    记一起动态库加载错误问题排查过程
    DNS缓存
    C输出大于127的ACSII字符
    Mint17 一些安装备忘
  • 原文地址:https://www.cnblogs.com/tq1226112215/p/3613860.html
Copyright © 2011-2022 走看看