昨天我們介紹了一款HTML5 文件上傳 的jQuery插件: jQuery HTML5 uploader ,今天我們將開發(fā)一個簡單的叫upload center的圖片上傳程序,允許用戶使用拖拽方式來上傳電腦上的圖片,使用現(xiàn)在瀏覽器支持新的HTML5 API。
?
圖片將會有一個預覽和進度條,都由客戶端控制。目前,圖片都保存在服務器上的一個目錄里,當然你可以自己加強相關功能。
?
?
?
什么是HTML 文件上傳 ?
使用HTML5上傳文件其實綜合使用了3種技術,新的 File Reader API ,還有新的 Drag &Drop API ,以及AJAX技術(包含2進制的數(shù)據(jù)傳輸)。這里是一個簡單HTML5文件的描述:
?
1. 用戶拖放一個或者多個文件到瀏覽器的窗口。支持Drap &Drop API的瀏覽器將會觸發(fā)一個事件,以及相關的其它信息,包括一個拖拽文件列表。
2. 使用File Reader API, 我們以2進制方式讀取文件,保存在內存中。
3. 使用XMLHttpRequest的新sendAsBinary方法 ,發(fā)送文件數(shù)據(jù)到服務器。
?
聽起來是不是有點復雜?是的,可以使用一些優(yōu)化。幸運的是,這里有些jQuery的插件可以幫助我們。其中有個插件叫 Filedrop ,是一個實現(xiàn)這個功能的插件,提供了限制最大文件體積和指定擦llback的特性,這些特性對于你整合這些功能非常有幫助。
?
目前 文件上傳 功能只能在 Firefox 和 Chrome 上正常工作,但是將發(fā)布的主流瀏覽器也會支持這些功能。一個簡單的fallback解決方案是顯示一個一般的 文件上傳 對話框。但是今天我們這里例子講不這樣設計,我們專注于HTML5的使用。
?
我們開始正式開發(fā)!
?
HTML代碼
這個上傳程序的html非常簡單。我們使用一個一般的HTML5文檔,包括了script.js文件,F(xiàn)iledrop插件和jQuery類庫。
?
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有關的唯一一個div是#dropbox。我們將這個元素傳入插件。插件將會判斷是否一個文件被拖放到上面。當發(fā)現(xiàn)有錯誤的時候信息span將會被更新(例如,如果瀏覽器不支持和這個應用有關的HTML5 API的時候)。
?
?
最后,當你拖放一個文件,我們的jQuery代碼將會顯示一個預覽,如下:
<div class="preview done">
<span class="imageHolder">
<img src="" />
<span class="uploaded"></span>
</span>
<div class="progressHolder">
<div class="progress"></div>
</div>
</div>
?
以上代碼片斷包含了一個圖片預覽和一個進度條。整個預覽帶有".done" class,可以讓".upload" span顯示。這個span將有綠色的背景標示,暗示上傳完成了。
?
接下來,我們看看script.js文件!
?
jQuery代碼
所有的實際文件傳送功能都由Filedrop插件完成,我們只是簡單的調用并且設置擦llback,因此我們可以直接使用。我們將在下一個部分書寫一個PHP腳本處理服務器段的 文件上傳 功能。
?
第一個步驟是書寫一個輔助功能接受一個文件對象(一個特別的由瀏覽器創(chuàng)建的對象,包含名字,路徑和大小)。以及預覽的標簽。
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的預覽標簽。我們得到圖片的DataURL并且添加為圖片源。每一個都被添加到dropbox容器里。
?
現(xiàn)在我們調用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);
}
});
?
使用這個,每一個正確的圖片文件被拖放到#dropbox div都會被上傳到post_file.php。
?
PHP Code
PHP這邊的代碼,和一般的表單上傳沒有太多區(qū)別。 這意味著你可以簡單的提供fallback來重用后臺功能。
// 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);
}
?
這段代碼運行一些http檢查,并且驗證文件擴展。我們不想保存任何文件,所以這個我們直接刪除。
?
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是絕對定位的。修改width用來做一個自然進度的標示。使用0.25 突然四體on,你會看到一個動畫的增量效果。
?
全部代碼完畢。
?
大家可以用這個教程做為HTML5的 文件上傳 服務的起點。有任何建議或者評論,只給我們在下方留言。
?
?
來源: http://www.starming.com/index.php?action=plugin&v=wave&tpl=union&ac=viewgrouppost&gid=34464&tid=17975
?
?
?
?
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

