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 += '\nThe number of files selected exceeds the remaining upload limit (' + errorMsg + ').';
                } else {
                    this.queueData.errorMsg += '\nThe number of files selected exceeds the queue size limit (' + settings.queueSizeLimit + ').';
                }
                break;
            case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                this.queueData.errorMsg += '\nThe file "' + file.name + '" exceeds the size limit (' + settings.fileSizeLimit + ').';
                break;
            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                this.queueData.errorMsg += '\nThe file "' + file.name + '" is empty.';
                break;
            case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:      //這邊bug  SWFUpload.QUEUE_ERROR.INVALID_FILETYPE
                this.queueData.errorMsg += '\nThe 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM