昨天我們介紹了一款HTML5 文件上傳 的jQuery插件: jQuery HTML5 uploader ,今天我們將開(kāi)發(fā)一個(gè)簡(jiǎn)單的叫upload center的圖片上傳程序,允許用戶使用拖拽方式來(lái)上傳電腦上的圖片,使用現(xiàn)在瀏覽器支持新的HTML5 API。
?
圖片將會(huì)有一個(gè)預(yù)覽和進(jìn)度條,都由客戶端控制。目前,圖片都保存在服務(wù)器上的一個(gè)目錄里,當(dāng)然你可以自己加強(qiáng)相關(guān)功能。
?
?
?
什么是HTML 文件上傳 ?
使用HTML5上傳文件其實(shí)綜合使用了3種技術(shù),新的 File Reader API ,還有新的 Drag &Drop API ,以及AJAX技術(shù)(包含2進(jìn)制的數(shù)據(jù)傳輸)。這里是一個(gè)簡(jiǎn)單HTML5文件的描述:
?
1. 用戶拖放一個(gè)或者多個(gè)文件到瀏覽器的窗口。支持Drap &Drop API的瀏覽器將會(huì)觸發(fā)一個(gè)事件,以及相關(guān)的其它信息,包括一個(gè)拖拽文件列表。
2. 使用File Reader API, 我們以2進(jìn)制方式讀取文件,保存在內(nèi)存中。
3. 使用XMLHttpRequest的新sendAsBinary方法 ,發(fā)送文件數(shù)據(jù)到服務(wù)器。
?
聽(tīng)起來(lái)是不是有點(diǎn)復(fù)雜?是的,可以使用一些優(yōu)化。幸運(yùn)的是,這里有些jQuery的插件可以幫助我們。其中有個(gè)插件叫 Filedrop ,是一個(gè)實(shí)現(xiàn)這個(gè)功能的插件,提供了限制最大文件體積和指定擦llback的特性,這些特性對(duì)于你整合這些功能非常有幫助。
?
目前 文件上傳 功能只能在 Firefox 和 Chrome 上正常工作,但是將發(fā)布的主流瀏覽器也會(huì)支持這些功能。一個(gè)簡(jiǎn)單的fallback解決方案是顯示一個(gè)一般的 文件上傳 對(duì)話框。但是今天我們這里例子講不這樣設(shè)計(jì),我們專注于HTML5的使用。
?
我們開(kāi)始正式開(kāi)發(fā)!
?
HTML代碼
這個(gè)上傳程序的html非常簡(jiǎn)單。我們使用一個(gè)一般的HTML5文檔,包括了script.js文件,F(xiàn)iledrop插件和jQuery類庫(kù)。
?
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>HTML5 File Drag and Drop Upload with jQuery and PHP | Tutorialzine Demo</title> <!-- Our CSS stylesheet file --> <link rel="stylesheet" href="assets/css/styles.css" /> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <header> <h1>HTML5 File Upload with jQuery and PHP</h1> </header> <div id="dropbox"> <span class="message">Drop images here to upload. <br /><i>(they will only be visible to you)</i></span> </div> <!-- Including The jQuery Library --> <script src="http://code.jquery.com/jquery-1.6.3.min.js"></script> <!-- Including the HTML5 Uploader plugin --> <script src="assets/js/jquery.filedrop.js"></script> <!-- The main script file --> <script src="assets/js/script.js"></script> </body> </html>
?
和Filedrop有關(guān)的唯一一個(gè)div是#dropbox。我們將這個(gè)元素傳入插件。插件將會(huì)判斷是否一個(gè)文件被拖放到上面。當(dāng)發(fā)現(xiàn)有錯(cuò)誤的時(shí)候信息span將會(huì)被更新(例如,如果瀏覽器不支持和這個(gè)應(yīng)用有關(guān)的HTML5 API的時(shí)候)。
?
?
最后,當(dāng)你拖放一個(gè)文件,我們的jQuery代碼將會(huì)顯示一個(gè)預(yù)覽,如下:
<div class="preview done"> <span class="imageHolder"> <img src="" /> <span class="uploaded"></span> </span> <div class="progressHolder"> <div class="progress"></div> </div> </div>
?
以上代碼片斷包含了一個(gè)圖片預(yù)覽和一個(gè)進(jìn)度條。整個(gè)預(yù)覽帶有".done" class,可以讓".upload" span顯示。這個(gè)span將有綠色的背景標(biāo)示,暗示上傳完成了。
?
接下來(lái),我們看看script.js文件!
?
jQuery代碼
所有的實(shí)際文件傳送功能都由Filedrop插件完成,我們只是簡(jiǎn)單的調(diào)用并且設(shè)置擦llback,因此我們可以直接使用。我們將在下一個(gè)部分書(shū)寫(xiě)一個(gè)PHP腳本處理服務(wù)器段的 文件上傳 功能。
?
第一個(gè)步驟是書(shū)寫(xiě)一個(gè)輔助功能接受一個(gè)文件對(duì)象(一個(gè)特別的由瀏覽器創(chuàng)建的對(duì)象,包含名字,路徑和大小)。以及預(yù)覽的標(biāo)簽。
var template = '<div class="preview">'+ '<span class="imageHolder">'+ '<img />'+ '<span class="uploaded"></span>'+ '</span>'+ '<div class="progressHolder">'+ '<div class="progress"></div>'+ '</div>'+ '</div>'; function createImage(file){ var preview = $(template), image = $('img', preview); var reader = new FileReader(); image.width = 100; image.height = 100; reader.onload = function(e){ // e.target.result holds the DataURL which // can be used as a source of the image: image.attr('src',e.target.result); }; // Reading the file as a DataURL. When finished, // this will trigger the onload function above: reader.readAsDataURL(file); message.hide(); preview.appendTo(dropbox); // Associating a preview container // with the file, using jQuery's $.data(): $.data(file,preview); }
?
template 變量包含了HTML5的預(yù)覽標(biāo)簽。我們得到圖片的DataURL并且添加為圖片源。每一個(gè)都被添加到dropbox容器里。
?
現(xiàn)在我們調(diào)用filedrop插件:
$(function(){ var dropbox = $('#dropbox'), message = $('.message', dropbox); dropbox.filedrop({ // The name of the $_FILES entry: paramname:'pic', maxfiles: 5, maxfilesize: 2, // in mb url: 'post_file.php', uploadFinished:function(i,file,response){ $.data(file).addClass('done'); // response is the JSON object that post_file.php returns }, error: function(err, file) { switch(err) { case 'BrowserNotSupported': showMessage('Your browser does not support HTML5 file uploads!'); break; case 'TooManyFiles': alert('Too many files! Please select 5 at most!'); break; case 'FileTooLarge': alert(file.name+' is too large! Please upload files up to 2mb.'); break; default: break; } }, // Called before each upload is started beforeEach: function(file){ if(!file.type.match(/^image//)){ alert('Only images are allowed!'); // Returning false will cause the // file to be rejected return false; } }, uploadStarted:function(i, file, len){ createImage(file); }, progressUpdated: function(i, file, progress) { $.data(file).find('.progress').width(progress); } }); var template = '...'; function createImage(file){ // ... see above ... } function showMessage(msg){ message.html(msg); } });
?
使用這個(gè),每一個(gè)正確的圖片文件被拖放到#dropbox div都會(huì)被上傳到post_file.php。
?
PHP Code
PHP這邊的代碼,和一般的表單上傳沒(méi)有太多區(qū)別。 這意味著你可以簡(jiǎn)單的提供fallback來(lái)重用后臺(tái)功能。
// If you want to ignore the uploaded files, // set $demo_mode to true; $demo_mode = false; $upload_dir = 'uploads/'; $allowed_ext = array('jpg','jpeg','png','gif'); if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){ exit_status('Error! Wrong HTTP method!'); } if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){ $pic = $_FILES['pic']; if(!in_array(get_extension($pic['name']),$allowed_ext)){ exit_status('Only '.implode(',',$allowed_ext).' files are allowed!'); } if($demo_mode){ // File uploads are ignored. We only log them. $line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name'])); file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND); exit_status('Uploads are ignored in demo mode.'); } // Move the uploaded file from the temporary // directory to the uploads folder: if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){ exit_status('File was uploaded successfuly!'); } } exit_status('Something went wrong with your upload!'); // Helper functions function exit_status($str){ echo json_encode(array('status'=>$str)); exit; } function get_extension($file_name){ $ext = explode('.', $file_name); $ext = array_pop($ext); return strtolower($ext); }
?
這段代碼運(yùn)行一些http檢查,并且驗(yàn)證文件擴(kuò)展。我們不想保存任何文件,所以這個(gè)我們直接刪除。
?
CSS代碼
/*------------------------- Dropbox Element --------------------------*/ #dropbox{ background:url('../img/background_tile_3.jpg'); border-radius:3px; position: relative; margin:80px auto 90px; min-height: 290px; overflow: hidden; padding-bottom: 40px; width: 990px; box-shadow:0 0 4px rgba(0,0,0,0.3) inset,0 -3px 2px rgba(0,0,0,0.1); } #dropbox .message{ font-size: 11px; text-align: center; padding-top:160px; display: block; } #dropbox .message i{ color:#ccc; font-size:10px; } #dropbox:before{ border-radius:3px 3px 0 0; } /*------------------------- Image Previews --------------------------*/ #dropbox .preview{ width:245px; height: 215px; float:left; margin: 55px 0 0 60px; position: relative; text-align: center; } #dropbox .preview img{ max-width: 240px; max-height:180px; border:3px solid #fff; display: block; box-shadow:0 0 2px #000; } #dropbox .imageHolder{ display: inline-block; position:relative; } #dropbox .uploaded{ position: absolute; top:0; left:0; height:100%; width:100%; background: url('../img/done.png') no-repeat center center rgba(255,255,255,0.5); display: none; } #dropbox .preview.done .uploaded{ display: block; } /*------------------------- Progress Bars --------------------------*/ #dropbox .progressHolder{ position: absolute; background-color:#252f38; height:12px; width:100%; left:0; bottom: 0; box-shadow:0 0 2px #000; } #dropbox .progress{ background-color:#2586d0; position: absolute; height:100%; left:0; width:0; box-shadow: 0 0 1px rgba(255, 255, 255, 0.4) inset; -moz-transition:0.25s; -webkit-transition:0.25s; -o-transition:0.25s; transition:0.25s; } #dropbox .preview.done .progress{ width:100% !important; }
?
.progress div是絕對(duì)定位的。修改width用來(lái)做一個(gè)自然進(jìn)度的標(biāo)示。使用0.25 突然四體on,你會(huì)看到一個(gè)動(dòng)畫(huà)的增量效果。
?
全部代碼完畢。
?
大家可以用這個(gè)教程做為HTML5的 文件上傳 服務(wù)的起點(diǎn)。有任何建議或者評(píng)論,只給我們?cè)谙路搅粞浴?
?
?
來(lái)源: http://www.starming.com/index.php?action=plugin&v=wave&tpl=union&ac=viewgrouppost&gid=34464&tid=17975
?
?
?
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
