1. 程式人生 > >jquery uploadify 上傳控制元件ASP.NET使用總結

jquery uploadify 上傳控制元件ASP.NET使用總結

         一、微軟自帶的FileUpload的樣式不夠絢,再者現在這幾個專案中的使用,逼迫著不得不學習新的知識。

              最近一直在使用jquery easyui-1.4.2框架開發著小型的ERP應用程式,但是發現了一個問題,客戶那裡一直還在使用著oracle9i,windows server 2003,.net framework2.0-3.5這個讓我情何以堪,jquery easyui 中的dialo在IE6-7中樣式問題,不相容,也是讓人頭痛。這個先放下不管,今天分享的是jquery uploadify的使用心得 。為什麼要分享這個呢,主要原因,發現filebox這個控制元件並不相容IE6-7所有這個就是麻煩了。。。

         二、首先說明咱使用的是什麼版本的。如圖。

                                     

          三、專案是小型ERP系統,框架使用的是Jquery Easyui 1.4.1 

          四、言歸正傳。

                 該控制元件為基於jquery的檔案上傳控制元件,支援ajax無重新整理上傳,同時多個檔案同時上傳,上傳進行進度顯示,可刪除已上傳檔案。要求使用jquery1.4或以上版本,flash player 9.0.24以上。jquery uploadify有兩個版本,一個用flash,一個是html5。html5的需要付費~所以這裡只說flash版本的用法。

                 已加入個人設定的樣式,效果如圖:

                 

                 首先了解一下,jquery uploadify的引數設定:

                 屬性:

$('#file_upload').uploadify({
                auto:false, //接受true 或 false兩個值,當為true時選擇檔案後會自動上傳;為false時只會把選擇的檔案增加進佇列但不會上傳,這時只能使用upload的方法觸發上傳。不設定auto時預設為true
                buttonClass: "btn-class", //設定上傳按鈕的class
                buttonCursor: 'hand',//設定滑鼠移到按鈕上的開狀,接受兩個值'hand'和'arrow'(手形和箭頭)
                buttonImage: 'img/browse.png', //設定圖片按鈕的路徑(當你的按鈕是一張圖片時)。如果使用預設的樣式,你還可以建立一個滑鼠懸停狀態,但要把兩種狀態的圖片放在一起,並且預設的放上面,懸停狀態的放在下面(you can create a hover state for the button by stacking the off state above the hover state in the image)。這只是一個比較便利的選項,最好的方法還是把圖片寫在CSS裡面。
                buttonText: '<div>瀏覽</div>',//設定按鈕文字。值會被當作html渲染,所以也可以包含html標籤
                checkExisting: '/uploadify/check-exists.php', //接受一個檔案路徑。此檔案檢查正要上傳的檔名是否已經存在目標目錄中。存在時返回1,不存在時返回0(主要用做後臺判斷),預設為false
                debug: false, //開啟或關閉debug模式
                fileObjName:'FileData', //設定在後臺指令碼使用的檔名。舉個例子,在asp.net中,如果這個選項設定為'FileData',你可以使用HttpPostedFile file = Request.Files["FileData"];存取這個已經上傳的檔案。未設定,則後臺預設接收的引數名為:Filedata
                fileSizeLimit:'100MB', //設定上傳檔案的容量最大值。這個值可以是一個數字或者字串。如果是字串,接受一個單位(B,KB,MB,GB)。如果是數字則預設單位為KB。設定為0時表示不限制
                fileTypeExts: '*.*',//設定允許上傳的副檔名(也就是檔案型別)。但手動鍵入檔名可以繞過這種級別的安全檢查,所以你應該始終在服務端中檢查檔案型別。輸入多個副檔名時用分號隔開('*.jpg;*.png;*.gif;*.xlsx;*.xls;*.csv')
                fileTypeDesc: '檔案',//可選檔案的描述。這個值出現在檔案瀏覽視窗中的檔案型別下拉選項中。(chrome下不支援,會顯示為'自定義檔案',ie and firefox下可顯示描述)
                formData: {
                    'folder': 'UploadFiles', 'method': 'Import', 'UserInfo': Sessionid
                }, //通過get或post上傳檔案時,此物件提供額外的資料。如果想動態設定這些值,必須在onUploadStartg事件中使用settings的方法設定。當專案沒有許可權驗證的情況下,不需要考慮很多,只需要設定一些方法名稱上傳到哪個資料夾路徑下。當有Session或者Auth驗證時,必須向後臺傳送sessionId否則,Firefox和Chrome瀏覽器認為這是不安全的請求,到後臺會生成一個新的SessionId導致驗證無法通過。造成的原因:uploadify上傳的機制是基於flash的通道不一樣。看官網參考寫法:<a target=_blank href="http://www.uploadify.com/documentation/uploadify/formdata/">http://www.uploadify.com/documentation/uploadify/formdata/</a>
                height: 30,//設定按鈕的高度(單位px),預設為30.(不要在值裡寫上單位,並且要求一個整數,width也一樣)
                width: 120,//設定按鈕寬度(單位px),預設120
                itemTemplate:false,//模板物件。給增加到上傳佇列中的每一項指定特殊的html模板。模板格式請看官網<a target=_blank href="http://www.uploadify.com/documentation/uploadify/itemtemplate/">http://www.uploadify.com/documentation/uploadify/itemtemplate/</a>
                method:'post',//提交上傳檔案的方法,接受post或get兩個值,預設為post
                multi: false,//設定是否允許一次選擇多個檔案,true為允許,false不允許
                overrideEvents: [],//重寫事件,接受事件名稱的陣列作為引數。所設定的事件將可以被使用者重寫覆蓋
                preventCaching:true,//是否快取swf檔案。預設為true,會給swf的url地址設定一個隨機數,這樣它就不會被快取。(有些瀏覽器快取了swf檔案就會觸發不了裡面的事件)
                progressData: 'percentage',//設定檔案上傳時顯示資料,有‘percentage’ or ‘speed’兩個引數(百分比和速度)
                queueID: false,//設定上傳佇列DOM元素的ID,上傳的專案會增加進這個ID的DOM中。設定為false時則會自動生成佇列DOM和ID。預設為false
                queueSizeLimit: 999,//設定每一次上傳佇列中的檔案數量。注意並不是限制總的上傳檔案數量(那是uploadLimit).如果增加進佇列中的檔案數量超出這個值,將會觸發onSelectError事件。預設值為999
                removeCompleted: true,//是否移除掉佇列中已經完成上傳的檔案。false為不移除
                removeTimeout: 3,//設定上傳完成後刪除掉檔案的延遲時間,預設為3秒。如果removeCompleted為false的話,此屬性無用
                requeueErrors: false,//設定上傳過程中因為出錯導致上傳失敗的檔案是否重新加入佇列中上傳
                successTimeout: 30,//設定檔案上傳後等待伺服器響應的秒數,超出這個時間,將會被認為上傳成功,預設為30秒
                swf: 'uploadify.swf',//swf的相對路徑,必寫項
                uploader: location.href ,//伺服器端指令碼檔案路徑,必寫項或寫成'../Convert/HalfExg.aspx'
                uploadLimit: 999//上傳檔案的數量。達到或超出這數量會觸發onUploadError方法。預設999
            })

                         事件:

            Uploadify使用jquery推薦的外掛模式,這意味著所有方法的呼叫都保持在一個名稱空間裡。 呼叫這些不同的方法,只需要把方法當成第一個引數傳進uploadify裡呼叫就行。在這些方法後面增加引數會被傳進這個方法裡(這兩句翻譯得不是很順暢,附原文: To use the different method calls, simply call Uploadify on the DOM element with the method call as the first argument.Any additional arguments added after the method name are passed to the method.

cancel:取消第一個上傳的檔案,如果後面帶引數"*"則是取消掉整個上傳佇列,如$(el).uploadify('cancel', '*')

upload:上傳第一個上傳的檔案,如果後面帶引數"*"則上傳整個佇列,跟cancel一樣

destory:移除掉上傳組建,按html預設的方法上傳

disable:有true or false 兩個引數,表示是否禁止上傳按鈕,true表示禁止,false表示允許上傳

setting:返回或者更新一個例項的方法值,接受一個方法名的引數時是返回那個方法的值,當後面再跟一個引數,則是更新那個方法的值。如

$(el).uploadify('settings','buttonText','BROWSE'); //設定buttonText的值為BROWSE
$(el).uploadify('settings','buttonText') //返回buttonText的值

stop:停止正在上傳中的檔案或佇列

$('#file_upload').uploadify({    
                onCancel: function(file){
                        console.log('This file'+ file.name + 'was cancelled.')
                }, //檔案被移除出佇列時觸發,返回file引數
                onClearQueue: function(queueItemCount){
                    console.log(queueItemCount+'file(s) were removed frome the queue')
                }, //當呼叫cancel方法且傳入'*'這個引數的時候觸發,其實就是移除掉整個佇列裡的檔案時觸發,上面有說cancel方法帶*時取消整個上傳佇列
                onDestroy: function(){
                    //呼叫destroy方法的時候觸發
                },
                onDialogClose: function(queueData){
                    console.log(queueData.filesSelected+'\n'+queueData.filesQueued+'\r\n'+queueData.filesReplaced+'\r\n'+queueData.filesCancelled+'\r\n'+ queueData.filesErrored)
                },//關閉掉瀏覽檔案對話方塊時觸發。返回queueDate引數,有以下屬性:
                /*
                    filesSelected 瀏覽檔案對話方塊中選取的檔案數量
                    filesQueued 加入上傳佇列的檔案數
                    filesReplaced 被替換的檔案個數
                    filesCancelled 取消掉即將加入佇列中的檔案個數
                    filesErrored 返回錯誤的檔案個數
                */
                onDialogOpen:function(){
                    //開啟選擇檔案對話方塊時觸發
                },
                onDisable:function(){
                    //禁用uploadify時觸發(通過disable方法)
                },
                onEnalbe: function(){
                    //啟用uploadify時觸發(通過disable方法)
                },
                onFallback:function(){
                    //在初始化時檢測不到瀏覽器有相容性的flash版本時實觸發
                },
                onInit: function(instance){
                    console.log('The queue ID is'+ instance.settings.queueID)
                }, //每次初始化一個佇列時觸發,返回uploadify物件的例項
                onQueueComplete:function(queueData){
                    console.log(queueData.uploadsSuccessful+'\n'+queueData.uploadsErrored)
                }, //佇列中的檔案都上傳完後觸發,返回queueDate引數,有以下屬性:
                /*
                    uploadsSuccessful 成功上傳的檔案數量
                    uploadsErrored 出現錯誤的檔案數量
                */
                onSelect: function(file){
                    console.log(file.name)
                },//選擇每個檔案增加進佇列時觸發,返回file引數
                onSelectError: function(file,errorCode,errorMsg){
                    console.log(errorCode)
                    console.log(this.queueData.errorMsg)
                },//選擇檔案出錯時觸發,返回file,erroCode,errorMsg三個引數
                /*
                    errorCode是一個包含了錯誤碼的js物件,用來檢視事件中傳送的錯誤碼,以確定錯誤的具體型別,可能會有以下的常量:
                    QUEUE_LIMIT_EXCEEDED:-100 選擇的檔案數量超過設定的最大值;
                    FILE_EXCEEDS_SIZE_LIMIT:-110 檔案的大小超出設定
                    INVALID_FILETYPE:-130 選擇的檔案型別跟設定的不匹配

                    errorMsg 完整的錯誤資訊,如果你不重寫預設的事件處理器,可以使用‘this.queueData.errorMsg’ 存取完整的錯誤資訊
                */
                onSWFReady: function(){
                    //swf動畫載入完後觸發,沒有引數
                },
                onUploadComplete: function(file){
                    //在每一個檔案上傳成功或失敗之後觸發,返回上傳的檔案物件或返回一個錯誤,如果你想知道上傳是否成功,最後使用onUploadSuccess或onUploadError事件
                },
                onUploadError: function(file,errorCode,erorMsg,errorString){
                }, //一個檔案完成上傳但返回錯誤時觸發,有以下引數
                /*
                    file 完成上傳的檔案物件
                    errorCode 返回的錯誤程式碼
                    erorMsg 返回的錯誤資訊
                    errorString 包含所有錯誤細節的可讀資訊
                */
                onUploadProgress: function(file,bytesUploaded,bytesTotal,totalBytesUploaded,totalBytesTotal){
                    $('#pregress').html('總共需要上傳'+bytesTotal+'位元組,'+'已上傳'+totalBytesTotal+'位元組')
                },//每更新一個檔案上傳進度的時候觸發,返回以下引數
                /*
                    file 正上傳檔案物件
                    bytesUploaded 檔案已經上傳的位元組數
                    bytesTotal 檔案的總位元組數
                    totalBytesUploaded 在當前上傳的操作中(所有檔案)已上傳的總位元組數
                    totalBytesTotal 所有檔案的總上傳位元組數
                */
                onUploadStart: function(file){
                    console.log('start update')
                },//每個檔案即將上傳前觸發
                onUploadSuccess: function(file,data,respone){
                    alert( 'id: ' + file.id
                           + ' - 索引: ' + file.index
                + ' - 檔名: ' + file.name
                + ' - 檔案大小: ' + file.size
                + ' - 型別: ' + file.type
                + ' - 建立日期: ' + file.creationdate
                + ' - 修改日期: ' + file.modificationdate
                + ' - 檔案狀態: ' + file.filestatus
                + ' - 伺服器端訊息: ' + data
                + ' - 是否上傳成功: ' + response);
                }
                //每個檔案上傳成功後觸發              
})

                     
下面是具體使用:

首先:

page頁面新增引用:

<link href="../Scripts/uploadify/uploadify.css" rel="stylesheet" />
<script type="text/javascript" src="Scripts/jquery-1.10.2.min.js"></script>
<script src="../Scripts/uploadify/jquery.uploadify-3.1.min.js"></script>

頁面使用:

頁面自己寫的樣式,比較臭 ,見笑了,哈哈~

 <table class="tb-import">
                <tr>
                    <td class="odd">選擇檔案:</td>
                    <td style="text-align: left; padding-left: 10px;" colspan="3">
                        <div id="divupup" style="z-index: 2;  padding: 0px; margin: 0px; width: 600px; height: 30px; position: absolute; display: inline-block;">
                            <input type="file" name="uploadify" id="upup" />
                        </div>
                        <div style="z-index: 3; padding: 0px; display: inline-block; position: relative; margin-left: 90px;">
                            <a href="javascript:$('#upup').uploadify('upload')" class="easyui-linkbutton" data-options="iconCls:'icon-undo'">匯入</a>
                            <a href="../DownLoad/Exg.csv" class="down-file">模板檔案下載</a>
                        </div>
                    </td>
                </tr>
            </table>

JavaScript 程式碼如下:

 <script type="text/javascript">
 //var auth = "<% = Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>";
        var Sessionid = "<%= Session.SessionID %>";//以上兩個全域性變數結合Global.asax中程式碼使用,才能解決在Firefox和chrome瀏覽器sessionid同步問題。

   $(function() {

   $("#upup").uploadify({
                'swf': '../Scripts/uploadify/uploadify.swf?var=' + new Date().getTime(),
                'uploader': location.href,
                'buttonText': '瀏覽',
                'height': 24,
                'queueID': false,
                'width': 80,
                'multi': false,
                'fileTypeExts': '*.xlsx;*.xls;*.csv',
                'fileTypeDesc': '*.xlsx;*.xls;*.csv',
                'formData': { 'folder': 'UploadFiles', 'method': 'Import', 'UserInfo': Sessionid },
                'auto': false,
                'progressData': 'all',
                'removeCompleted': true,
                'onUploadSuccess': function(file, data, response) { 
                    if (data.substring(0, 1) == "1") {
                        $.messager.alert('提示', data.substr(1), 'info');
                        $('#upup').uploadify('cancel');
                        $("#dgList").datagrid("reload");
                    } else
                        $.messager.alert('提示', data.toString(), 'info');
                }

            });
         AddCss();
 });
   ///以下3個js處理瀏覽器下樣式不相容的問題
  function AddCss() {
            var browser = getBrowserInfo().toString();
            var verinfo = (browser + "").replace(/[^0-9.]/ig, "");
            var number = parseInt(verinfo);
            if (browser.substr(0, 4) == "msie" && number < 8) {
                $("#divupup").css("margin-left", "-90px");
            }

            bro();
        }

        function bro() {
            var is360 = false;
            var isIE = false;
            if (window.navigator.appName.indexOf("Microsoft") != -1) {
                isIE = true;
            }
            if (isIE && (window.navigator.userProfile + '') == 'null') {
                is360 = true;
            }
            if (is360) {
                $("#divupup").css("margin-left", "-90px");
            }
        }


        function getBrowserInfo() {
            var agent = navigator.userAgent.toLowerCase();

            var regStrIe = /msie [\d.]+;/gi;
            var regStrFf = /firefox\/[\d.]+/gi;
            var regStrChrome = /chrome\/[\d.]+/gi;
            var regStrSaf = /safari\/[\d.]+/gi;
            //IE
            if (agent.indexOf("msie") > 0) {
                return agent.match(regStrIe);
            }

            //firefox
            if (agent.indexOf("firefox") > 0) {
                return agent.match(regStrFf);
            }

            //Chrome
            if (agent.indexOf("chrome") > 0) {
                return agent.match(regStrChrome);
            }

            //Safari
            if (agent.indexOf("safari") > 0 && agent.indexOf("chrome") < 0) {
                return agent.match(regStrSaf);
            }
         

            return "";
        }

 </script>



  注意事項(最關鍵的一步):

          全域性處理程式Global.asax中程式碼如下:

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
             //此處為Session許可權驗證
            try
            {
                //此處設定的值必須為登入視窗設定的session值
                const string sessionPermissionsKey = "UserInfo";
                //ASP.NET程式的sessioncookiename值必須為  ASP.NET_SessionId 否則獲取不到sessionid
                const string sessionCookieName = "ASP.NET_SessionId";

                if (HttpContext.Current.Request.Form[sessionPermissionsKey] != null)
                {
                    UpdateCookie(sessionCookieName, HttpContext.Current.Request.Form[sessionPermissionsKey]);
                }
                else if (HttpContext.Current.Request.QueryString[sessionPermissionsKey] != null)
                {
                    UpdateCookie(sessionCookieName, HttpContext.Current.Request.QueryString[sessionPermissionsKey]);
                }
            }
            catch (Exception)
            {
                // ignored
            }


            //此處是身份驗證
            try
            {

                const string authPermissionsKey = "AUTHID";
                string authCookieName = FormsAuthentication.FormsCookieName;
                if (HttpContext.Current.Request.Form[authPermissionsKey] != null)
                {
                    UpdateCookie(authCookieName, HttpContext.Current.Request.Form[authPermissionsKey]);
                }
                else if (HttpContext.Current.Request.QueryString[authPermissionsKey] != null)
                {
                    UpdateCookie(authCookieName, HttpContext.Current.Request.QueryString[authPermissionsKey]);
                }
            }
            catch (Exception)
            {
                // ignored
            }

        }

        private void UpdateCookie(string cookieKey, string cookieValue)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookieKey);
            if (null == cookie)
            {
                cookie = new HttpCookie(cookieKey);
            }
            cookie.Value = cookieValue;
            HttpContext.Current.Request.Cookies.Set(cookie); //重新設定請求中的cookie值,將伺服器端的session值賦值給它
        }
               以上為jquery uploadify的使用總結 ,如有更好的更方便的控制元件則必積極和大夥共同學習~