1. 程式人生 > >檔案上傳相容IE10以下(Webuploader使用)-

檔案上傳相容IE10以下(Webuploader使用)-

剛開始進入公司,公司專案中的檔案上傳使用了HTML5的input型別為file,這在IE9版本一下就比較尷尬。由於公司網站流程中需要大量使用上傳功能,所以初入這便成了出入公司的我第一項工作。

最初我的解決方案利用js是判斷瀏覽器,在頁面上謝了兩套程式碼,當是IE版本時候,就移除HTML5的程式碼,反之亦然。最初在IE下使用了uoloadify,也進行了二次封裝,不過程式碼被我後來更新掉了,就不給大家展示了,推薦一個API地址http://www.mamicode.com/info-detail-506696.html。後來項工作不是很忙,我感覺這樣分開寫不利於頁面程式碼的簡潔,也不利於別人使用,所以又想了個辦法,使用百度webuolpader,可以保證頁面程式碼的統一性,感謝百度webuploader團隊。http://fex.baidu.com/webuploader/getting-started.html

下面是小弟進行的二次封裝,其實我發現現在大部分的前段外掛都是基於事件程式設計,方便快捷。

使用Web Uploader檔案上傳需要引入三種資源:JS, CSS, SWF。

<!--引入CSS-->

<link rel="stylesheet" type="text/css" href="webuploader資料夾/webuploader.css">


<!--引入JS-->
<script type="text/javascript" src="webuploader資料夾/webuploader.js"></script>

swf檔案地址需要指定在初始化中

/**
 * 上傳檔案呼叫
 * @param inputId     按鈕ID
 * @param inputList   檔案區域
 * @param submit       上傳按鈕ID
 * @param url           上傳URL
 * @param filename      後臺接受名字
 * @param type       上傳型別  圖片img
 */
function intWebUploder(inputId,inputList,submit,url,filename,type) {
	var $ = jQuery,
		$list = $('#'+inputList),
        $btn = $('#'+submit),
         // 優化retina, 在retina下這個值是2
        ratio = window.devicePixelRatio || 1,
        //定義略縮圖大小
        thumbnailWidth = 150 * ratio,
        thumbnailHeight = 150 * ratio,
        // Web Uploader例項
        uploader;
	//定義選擇檔案型別  
	if(type=='img'){
      	var mycars=new Array('圖片上傳','gif,jpg,jpeg,bmp,png','image/*');
      	var fileSize=5242880;
      }else if(type=='file'){
    	  var mycars=new Array('檔案上傳','*','/*');
    	  var fileSize=52428800;
      }
    	// 初始化Web Uploader
    	uploader = WebUploader.create({
    	// 自動上傳。
        auto: false,
        fileNumLimit:1,
        fileSingleSizeLimit:fileSize,
        // swf檔案路徑
        swf: basePath+'webuploader/Uploader.swf',
        // 檔案接收服務端。
        server: basePath+url,
        // 內部根據當前執行是建立,可能是input元素,也可能是flash.
        pick: {
        	id:'#'+inputId,
        	innerHTML:'選擇檔案',
        	},
        	// 只允許選擇檔案,可選。
        accept:{
            title: mycars[0],
            extensions: mycars[1],
            mimeTypes: mycars[2]
        },
        fileVal:filename,
        });
//   上傳按鈕呼叫方法
     $btn.on( 'click', function() {
   	 var stats = uploader.getFiles();
    	 if(type=='img'){
    		 imageUpload(inputId);//自定義上傳操作
    		 if(stats[0]!=undefined){uploader.upload();}
    		 else{ if(inputId=='filePickerHead'){if(!$(".headimg-click img").hasClass("erp-border-red")){
				 											errorMsg("請選擇檔案");}}
			 									else{
			 										errorMsg("請選擇檔案");
			 									}
	    			 
    		}//else
    	}else if(type=='file'){
    		var boolen=fileUpload(inputId);//自定義檔案上傳方法  需返回boolean
    		if(boolen==true){
    			 if(stats[0]!=undefined){uploader.upload();}
    			 else{errorMsg("請選擇檔案");}
    		}
    	}//else if
});//按鈕
    
    //當檔案被新增之前操作
     uploader.on( 'beforeFileQueued', function( file ){
    	 $list.empty();
    	uploader.reset();
    	 });
    
    // 當有檔案新增進來的時候
    uploader.on( 'fileQueued', function( file ) {
    	$(".headimg-click img").removeClass("erp-border-red");
    	$("#selectFile"+inputId).text(file.name);
//    	$("#headinput").val(file.name);
    	var $li = $(
//    			'<input type="text"  value="'+ file.name +'" />'+
                '<div id="' + file.id + '" class="file-item thumbnail" style="margin-left:110px;">' +
                    '<img>' +
//                    '<div class="info" style="color:white;">' + file.name + '</div>' +
                    
                '</div>'
                ),
            $img = $li.find('img');

        $list.append( $li );
        // 建立縮圖
       uploader.makeThumb( file, function( error, src ) {
            if ( error ) {
               if(type=='img'){$img.replaceWith('<span>不能預覽</span>');} 
               else if(type=='file'){$img.hide();} 
                return;
            }
            $img.attr( 'src', src );
        }, thumbnailWidth, thumbnailHeight );
       
    });
//檔案上傳前
    uploader.on('uploadStart',function(file){
    	if(type=="file"){var data=dataSend(inputId);
    	   uploader.option('formData',data);}
    });

    // 檔案上傳過程中建立進度條實時顯示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
    	var $li = $( '#'+file.id ),
        $percent = $li.find('.progress .progress-bar');
    // 避免重複建立
    if ( !$percent.length ) {
        $percent = $('<div id="asdf" class="progress progress-striped active " style="width: 500px;">' +
          '<div class="progress-bar" role="progressbar" style="width: 0%;background-color: #33FF66;border:1px solid #33CC66;">' +
          '</div>' +
        '</div>').appendTo( $li ).find('.progress-bar');
       $('.progress progress-striped active .progress-bar').progressbar({display_text: 'fill'});
        }
    
    $li.find('p.state').text('上傳中');
    $percent.css( 'width', percentage * 100 + '%' );
    });

    // 檔案上傳成功,給item新增成功class, 用樣式標記上傳成功。
    uploader.on( 'uploadSuccess', function( file ,response) {
    	$( '#'+file.id ).addClass('upload-state-done');
    	var resultdata=response._raw;
    	if(type=='img'){
      		var imgUrl = resultdata.split(",")[1].replace("##","");
      		imageSuccess(inputId,imgUrl);
      	}else if(type=='file'){
      		if(resultdata.indexOf(",")>-1){
      			var imgUrl = resultdata.split(",")[1].replace("##","");
      			fileSuccess(inputId,imgUrl);
      		}else{
      			var imgUrl='';
      			fileSuccess(inputId,imgUrl);
      		}
      		
      }
    	 successMsg("上傳成功!");
          uploader.removeFile(uploader.getFile(file.id),true);
    	 setTimeout('$(".uploader-list").empty();', 2000);
   });
    
    // 檔案上傳失敗,現實上傳出錯。
    uploader.on( 'uploadError', function( file ) {
    errorMsg("上傳失敗!");
    setTimeout('$(".uploader-list").empty();', 2000);
     });

    // 完成上傳完了,成功或者失敗,都執行。
    uploader.on( 'uploadComplete', function( file ) {
    	 });
};
基於事件程式設計,我們可以在發生各時間的時候新增函式,比方說上傳頭像成功後需要重新整理頁面頭像,可以將方法寫在
imageSuccess(inputId,imgUrl);函式中。將封裝好的js放入base.js方便大家都是用。封裝後不用每個上傳位置都寫大量初始化程式碼。
頁面HTML<pre name="code" class="javascript">$(function() {
		var headurl = 'user/uploadUserInfoHeadPhoto.do';
	   	var Certificate= 'user/uploadUserCertificate.do';
	  	 var UserIdPhoto='user/uploadUserIdPhoto.do';
		intWebUploder('filePickerHead','fileListHead','ctlBtn',headurl,'uFile','img');
	  	intWebUploder('filePickerCertificate','fileListCertificate','ctlBtnCertificate',Certificate,'uFileQuali','img');
	   intWebUploder('filePickerUserIdPhoto','fileListUserIdPhoto','ctlBtnUserIdPhoto',UserIdPhoto,'photos','img');
	});
如此簡單。使用外掛可以快速幫我們解決問題,也算是初學者站在巨人的肩膀上吧大笑
</pre><pre name="code" class="javascript" style="font-size: 18px;">
在使用中我還發現了一個問題,在使用bootstrp的模態框時,初始化後的上傳按鈕會出現點選沒有反應的現象。以下是解決辦法
在webuploader.js原始碼下修改   頁面在載入完後點擊按鈕無效,按下f12或者重新整理後正常。現在的解決方案是:在webuploader.js 1775行左右的refresh方法裡,加入以下程式碼:
shimContainer.css({
width: '100%',
height: '100%'
});
問題似乎解決了。
試試看


Webuploader修改外掛預設上傳引數