界面样式我是参考了一个国外的相册网站,改动不大,只是把鸟语转换成中文,以及上传时的样式也进行了改动,之所以选这个的原因就是,我很容易做扩展,它支持3种方式添加图片,一种拖拽上传,一种常规的选择文件上传,另外的就是添加网络图片。它很巧妙的把三种上传模式整合到了一起,而且你可以用IE浏览器浏览下,如果不支持HTML5,是没有拖拽上传图片的提示的,如图:

  拖拽上传最重要的就是js部分的代码,它实现了70%的功能,另外30%仅仅是把图片信息提交到后台,然后做对应的处理,比如压缩啊,裁剪啊云云。所以先来看下js实现代码吧。

代码如下 复制代码
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="js/jquery-1.7.1.min.js"></script>
<style>
.dashboard_target_box{width:250px;height:105px;border:3px dashed #E5E5E5;text-align:center;position:absolute;z-index:2000;top:0;left:0;cursor:pointer}
.dashboard_target_box.over{border:3px dashed #000;background:#ffa}
.dashboard_target_messages_container{display:inline-block;margin:12px 0 0;position:relative;text-align:center;height:44px;overflow:hidden;z-index:2000}
.dashboard_target_box_message{position:relative;margin:4px auto;font:15px/18px helvetica,arial,sans-serif;font-size:15px;color:#999;font-weight:normal;width:150px;line-height:20px}
.dashboard_target_box.over #dtb-msg1{color:#000;font-weight:bold}
.dashboard_target_box.over #dtb-msg3{color:#ffa;border-color:#ffa}
#dtb-msg2{color:orange}
#dtb-msg3{display:block;border-top:1px #EEE dotted;padding:8px 24px}
</style>
<script>
$().ready(function(){
if($.browser.safari || $.browser.mozilla){
$('#dtb-msg1 .compatible').show();
$('#dtb-msg1 .notcompatible').hide();
$('#drop_zone_home').hover(function(){
$(this).children('p').stop().animate({top:'0px'},200);
},function(){
$(this).children('p').stop().animate({top:'-44px'},200);
});
//功能实现
$(document).on({
dragleave:function(e){
e.preventDefault();
$('.dashboard_target_box').removeClass('over');
},
drop:function(e){
e.preventDefault();
//$('.dashboard_target_box').removeClass('over');
},
dragenter:function(e){
e.preventDefault();
$('.dashboard_target_box').addClass('over');
},
dragover:function(e){
e.preventDefault();
$('.dashboard_target_box').addClass('over');
}
});
var box = document.getElementById('target_box');
box.addEventListener("drop",function(e){
e.preventDefault();
//获取文件列表
var fileList = e.dataTransfer.files;
var img = document.createElement('img');
//检测是否是拖拽文件到页面的操作
if(fileList.length == 0){
$('.dashboard_target_box').removeClass('over');
return;
}
//检测文件是不是图片
if(fileList[0].type.indexOf('image') === -1){
$('.dashboard_target_box').removeClass('over');
return;
}

if($.browser.safari){
//Chrome8+
img.src = window.webkitURL.createObjectURL(fileList[0]);
}else if($.browser.mozilla){
//FF4+
img.src = window.URL.createObjectURL(fileList[0]);
}else{
//实例化file reader对象
var reader = new FileReader();
reader.onload = function(e){
img.src = this.result;
$(document.body).appendChild(img);
}
reader.readAsDataURL(fileList[0]);
}
var xhr = new XMLHttpRequest();
xhr.open("post", "test.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.upload.addEventListener("progress", function(e){
$("#dtb-msg3").hide();
$("#dtb-msg4 span").show();
$("#dtb-msg4").children('span').eq(1).css({width:'0px'});
$('.show').html('');
if(e.lengthComputable){
var loaded = Math.ceil((e.loaded / e.total) * 100);
$("#dtb-msg4").children('span').eq(1).css({width:(loaded*2)+'px'});
}
}, false);
xhr.addEventListener("load", function(e){
$('.dashboard_target_box').removeClass('over');
$("#dtb-msg3").show();
$("#dtb-msg4 span").hide();
var result = jQuery.parseJSON(e.target.responseText);
alert(result.filename);
$('.show').append(result.img);
}, false);

var fd = new FormData();
fd.append('xfile', fileList[0]);
xhr.send(fd);
},false);
}else{
$('#dtb-msg1 .compatible').hide();
$('#dtb-msg1 .notcompatible').show();
}
});
</script>
</head>

<body>
<div id="target_box" class="dashboard_target_box">
<div id="drop_zone_home" class="dashboard_target_messages_container">
<p id="dtb-msg2" class="dashboard_target_box_message" style="top:-44px">选择你的图片<br>开始上传</p>
<p id="dtb-msg1" class="dashboard_target_box_message" style="top:-44px">
<span class="compatible" style="display:inline">拖动图片到</span><span class="notcompatible" style="display:none">点</span>这里<br>开始上传图片
</p>
</div>
<p id="dtb-msg3" class="dashboard_target_box_me(www.111cn.net)ssage">选择网络图片</p>
<p id="dtb-msg4" class="dashboard_target_box_message" style="position:relative">
<span style="display:none;width:200px;height:2px;background:#ccc;left:-25px;position:absolute;z-index:1"></span>
<span style="display:none;width:0px;height:2px;background:#09F;left:-25px;position:absolute;z-index:2"></span>
</p>
</div>
<div class="show" style="float:left;width:300px;height:150px;border:1px solid red;margin-top:200px;overflow:hidden;"></div>
</body>
</html>

test.php文件

代码如下 复制代码
<?php
$r = new stdClass();
header('content-type: application/json');
$maxsize = 10; //Mb
if($_FILES['xfile']['size'] > ($maxsize * 1048576)){
$r->error = "图片大小">图片大小不超过 $maxsize MB";
}
$folder = 'files/';
if(!is_dir($folder)){
mkdir($folder);
}
$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
if(!is_dir($folder)){
mkdir($folder);
}

if(preg_match('/image/i', $_FILES['xfile']['type'])){
$filename = $_POST['value'] ? $_POST['value'] : $folder . sha1(@microtime() . '-' . $_FILES['xfile']['name']) . '.jpg';
}else{
$tld = split(',', $_FILES['xfile']['name']);
$tld = $tld[count($tld) - 1];
$filename = $_POST['value'] ? $_POST['value'] : $folder . sha1(@microtime() . '-' . $_FILES['xfile']['name']) . $tld;
}

$types = Array('image/png', 'image/gif', 'image/jpeg');
if(in_array($_FILES['xfile']['type'], $types)){
$source = file_get_contents($_FILES["xfile"]["tmp_name"]);
imageresize($source, $filename, $_POST['width'], $_POST['height'], $_POST['crop'], $_POST['quality']);
}else{
move_uploaded_file($_FILES["xfile"]["tmp_name"], $filename);
}

$path = str_replace('test.php', '', $_SERVER['SCRIPT_NAME']);

$r->filename = $filename;
$r->path = $path;
$r->img = '<img src="' . $path . $filename . '" alt="image" />';

echo json_encode($r);

function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) {
$quality = $quality ? $quality : 80;
$image = imagecreatefromstring($source);
if ($image) {
// Get dimensions
$w = imagesx($image);
$h = imagesy($image);
if (($width && $w > $width) || ($height && $h > $height)) {
$ratio = $w / $h;
if (($ratio >= 1 || $height == 0) && $width && !$crop) {
$new_height = $width / $ratio;
$new_width = $width;
} elseif ($crop && $ratio <= ($width / $height)) {
$new_height = $width / $ratio;
$new_width = $width;
} else {
$new_width = $height * $ratio;
$new_height = $height;
}
} else {
$new_width = $w;
$new_height = $h;
}
$x_mid = $new_width * .5; //horizontal middle
$y_mid = $new_height * .5; //vertical middle
// Resample
error_log('height: ' . $new_height . ' - width: ' . $new_width);
$new = imagecreatetruecolor(round($new_width), round($new_height));
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
// Crop
if ($crop) {
$crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height);
imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height);
//($y_mid - ($height * .5))
}
// Output
// Enable interlancing [for progressive JPEG]
imageinterlace($crop ? $crop : $new, true);

$dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
if ($dext == '') {
$dext = $ext;
$destination .= '.' . $ext;
}
switch ($dext) {
case 'jpeg':
case 'jpg':
imagejpeg($crop ? $crop : $new, $destination, $quality);
break;
case 'png':
$pngQuality = ($quality - 100) / 11.111111;
$pngQuality = round(abs($pngQuality));
imagepng($crop ? $crop : $new, $destination, $pngQuality);
break;
case 'gif':
imagegif($crop ? $crop : $new, $destination);
break;
}
@imagedestroy($image);
@imagedestroy($new);
@imagedestroy($crop);
}
}
?>

from:http://www.111cn.net/wy/html5/41759.htm

html5+php实现文件拖动上传功能的更多相关文章

  1. HTML实现文件拖动上传

    在大型企业的开发过程中,很多比较有趣而实际的功能往往都是让大家望而却步,我给大家带来一个百度云盘和360云盘的HTML5多文件拖动上传技术: 1:记得导入:common-fileupload.jar包 ...

  2. HTML5实现图片文件异步上传

    原文:HTML5实现图片文件异步上传 利用HTML5的新特点做文件异步上传非常简单方便,本文主要展示JS部分,html结构.下面的代码并未使用第三发库,如果有参照,请注意一些未展现出来的代码片段.我这 ...

  3. asp.net 如何实现大文件断点上传功能?

    之前仿造uploadify写了一个HTML5版的文件上传插件,没看过的朋友可以点此先看一下~得到了不少朋友的好评,我自己也用在了项目中,不论是用户头像上传,还是各种媒体文件的上传,以及各种个性的业务需 ...

  4. HTML5+J2EE实现文件异步上传

    P.S. HTML5经过了W3C的8年努力,终于正式推广了.这次升级最大的就是升级了XMLHTTPRequest,让它变成了XMLHTTPRequest Level II(这有啥奇怪的?).这个对象现 ...

  5. 关于在Struts2框架下实现文件的上传功能

    struts2的配置过程 (1)在项目中加入jar包 (2)web.xml中filter(过滤器)的配置 <?xml version="1.0" encoding=" ...

  6. Servlet+Jsp实现图片或文件的上传功能

    首先,我们创建一个新的web工程,在工程的WebRoot目录下新建一个upload文件夹,这样当我们将该工程部署到服务器上时,服务器便也生成个upload文件夹,用来存放上传的资源. 然后,在WebR ...

  7. 简单的socket_server 和 socket_client(实现文件的上传功能)

    socket_server 客户端程序 import socket, os, json class Ftcplient(object): def __init__(self): "" ...

  8. HTML5实现多文件的上传示例代码

    [转自] http://www.jb51.net/html5/136791.html 主要用到的是<input>的multiple属性 代码如下: <input type=" ...

  9. 配置php.ini实现PHP文件上传功能

    本文介绍了如何配置php.ini实现PHP文件上传功能.其中涉及到php.ini配置文件中的upload_tmp_dir.upload_max_filesize.post_max_size等选项,这些 ...

随机推荐

  1. jquery.cookie.js结合asp.net实现最近浏览记录

    一.html代码 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ww ...

  2. Ubuntu IntelliJ IDEA 注冊碼與Gradle相關

    一.Ubuntu IntelliJ IDEA 注冊碼 在线免费生成IntelliJ IDEA 15.0(16.+)注册码 注冊參考:https://www.iteblog.com/idea/ 依次选择 ...

  3. Aerospike系列:4:简单的增删改查aql

    [root@localhost bin]# aql --help Usage: aql OPTIONS OPTIONS -h <host> The hostname to the serv ...

  4. Array相关的属性和方法

    这里只是做了相关的列举,具体的使用方法,请参考网址. Array 对象属性 constructor 返回对创建此对象的数组函数的引用. var test=new Array(); if (test.c ...

  5. java 解析excel工具类

      java 解析excel工具类 CreateTime--2018年3月5日16:48:08 Author:Marydon ReadExcelUtils.java import java.io.Fi ...

  6. python之模块contextlib 加强with语句而存在

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块contextlib,为加强with语句而存在 #特别注意:python3和python2 ...

  7. 使用std::find_if提取序列容器的子串

    一个需求是这样的,一个vector容器中,我需要提取满足一定条件的元素的序列.就比如,一个树形结构,我把该接口拍扁成vector容器,每个节点都有一个惟一ID. 以下就是根据特定的ID查找节点下的子节 ...

  8. 【jquery】多日期选择插件easyui date

    1.本次介绍一个好用的 多日期选择插件:EasyUI date,适用于:需要一次性选择多个日期,无需手动一个一个进行添加. 2.效果图: 3.下载地址:http://www.jeasyui.com/d ...

  9. Linux-中断的本质

    更好的参考:CPU的内部的中断 学习中断是为了理解信号,因为信号即软中断. 中断不是轮询!比如最常见的在UART通信过程中(收发数据),有两种方式,一种是中断,一种是轮询.如果中断是轮询,这两者就没区 ...

  10. java定时重启电脑程序demo

    下载地址:链接: https://pan.baidu.com/s/1HchKC0-gwDz-VU8eEQQMlw 提取码: 9fur