您的位置:首页 > Web前端 > JQuery

使用jQuery开发一个基于HTML5的漂亮图片拖拽上传web应用

2012-11-01 13:38 786 查看
今天我们将开发一个简单的叫upload center的图片上传程序,允许用户使用拖拽方式来上传电脑上的图片,使用现在浏览器支持新的HTML5
API。
图片将会有一个预览和进度条,都由客户端控制。目前,图片都保存在服务器上的一个目录里,当然你可以自己加强相关功能。



在线演示

在线下载

什么是HTML文件上传?

使用HTML5上传文件其实综合使用了3种技术,新的File Reader
API,还有新的Drag&Drop
API,以及AJAX技术(包含2进制的数据传输)。这里是一个简单HTML5文件的描述:

1. 用户拖放一个或者多个文件到浏览器的窗口。支持Drap&Drop API的浏览器将会触发一个事件,以及相关的其它信息,包括一个拖拽文件列表。

2. 使用File Reader API, 我们以2进制方式读取文件,保存在内存中。

3. 使用XMLHttpRequest的新sendAsBinary方法 ,发送文件数据到服务器。

听起来是不是有点复杂?是的,可以使用一些优化。幸运的是,这里有些jQuery的插件可以帮助我们。其中有个插件叫Filedrop,是一个实现这个功能的插件,提供了限制最大文件体积和指定擦llback的特性,这些特性对于你整合这些功能非常有帮助。

目前文件上传功能只能在FirefoxChrome上正常工作,但是将发布的主流浏览器也会支持这些功能。一个简单的fallback解决方案是显示一个一般的文件上传对话框。但是今天我们这里例子讲不这样设计,我们专注于HTML5的使用。

我们开始正式开发!

HTML代码

这个上传程序的html非常简单。我们使用一个一般的HTML5文档,包括了script.js文件,Filedrop插件和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。我们将这个元素传入插件。插件将会判断是否一个文件被拖放到上面。当发现有错误的时候信息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脚本处理服务器段的文件上传功能。

第一个步骤是书写一个辅助功能接受一个文件对象(一个特别的由浏览器创建的对象,包含名字,路径和大小)。以及预览的标签。

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容器里。

现在我们调用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这边的代码,和一般的表单上传没有太多区别。 这意味着你可以简单的提供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的文件上传服务的起点。有任何建议或者评论,只给我们在下方留言。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐