WebUploader是由Baidu WebFE(FEX)團隊開發的一個以HTML5/FLASH構建的現代檔案上傳組件。在現代的瀏覽器裡面能充分發揮HTML5的優勢,同時又不摒棄主流IE瀏覽器,沿用老的FLASH運行時,相容PC和移動端。它最大的特點是採用大檔案分區並發上傳,極大的提高了檔案上傳效率。touchend略要處理下。功能強大的檔案上傳外掛程式帶上傳進度 ,有興趣請直接下載源碼拿去用。
我們首先將css和相關js檔案載入。然後我們需要準備一個按鈕#imgPicker,和一個用來存放添加的檔案資訊列表的容器#fileList,在body中加入如下代碼: 選擇圖片
首先js建立Web Uploader執行個體: var uploader = WebUploader.create({ auto: true, // 選完檔案後,是否自動上傳 swf: 'js/Uploader.swf', // swf檔案路徑 server: 'upload.php', // 檔案接收服務端 pick: '#imgPicker', // 選擇檔案的按鈕。可選 // 只允許選擇圖片檔案。 accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } }); uploader.on( 'fileQueued', function( file ) { var $list = $("#fileList"), $li = $( '<div id="' + file.id + '" class="file-item thumbnail">' + '<img>' + '<div class="info">' + file.name + '</div>' + '</div>' ), $img = $li.find('img'); // $list為容器jQuery執行個體 $list.append( $li ); // 建立縮圖 uploader.makeThumb( file, function( error, src ) { if ( error ) { $img.replaceWith('<span>不能預覽</span>'); return; } $img.attr( 'src', src ); }, 100, 100 ); //100x100為縮圖尺寸 });// 檔案上傳過程中建立進度條即時顯示。 uploader.on( 'uploadProgress', function( file, percentage ) { var $li = $( '#'+file.id ), $percent = $li.find('.progress span'); // 避免重複建立 if ( !$percent.length ) { $percent = $('<p class="progress"><span></span></p>') .appendTo( $li ) .find('span'); } $percent.css( 'width', percentage * 100 + '%' ); }); // 檔案上傳成功,給item添加成功class, 用樣式標記上傳成功。 uploader.on( 'uploadSuccess', function( file, res ) { console.log(res.filePath);//這裡可以得到上傳後的檔案路徑 $( '#'+file.id ).addClass('upload-state-done'); }); // 檔案上傳失敗,顯示上傳出錯。 uploader.on( 'uploadError', function( file ) { var $li = $( '#'+file.id ), $error = $li.find('div.error'); // 避免重複建立 if ( !$error.length ) { $error = $('<div class="error"></div>').appendTo( $li ); } $error.text('上傳失敗'); }); // 完成上傳完了,成功或者失敗,先刪除進度條。 uploader.on( 'uploadComplete', function( file ) { $( '#'+file.id ).find('.progress').remove(); }); .prev{left: 20px} .next{right: 20px}PHP處理檔案上傳 upload.php接收上傳資料,將上傳的檔案儲存到伺服器相關目錄,並將上傳結果告知前端上傳組件。 這裡值得一提的是,如果設定了大檔案分區上傳,PHP將每次上傳的小檔案片臨時儲存,等最後檔案片全部接收完畢後再將這些臨時檔案片組合,成為一個完整的大檔案。 webuploader的分區上傳是把檔案分成若干份,然後向你定義的檔案接收端post資料,如果上傳的檔案大於分區的尺寸,就會進行分區,然後會在post的資料中添加兩個form元素chunk和chunks,前者標示當前分區在上傳分區中的順序(從0開始),後者代表總分區數。 關於upload.php中的代碼,這裡就不貼出來了,大家可以下載源碼來學習。 Web Uploader項目的官網地址:http://fex.baidu.com/webuploader/
這裡可以看示範效果 功能強大的檔案上傳外掛程式帶上傳進度