侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

html5 拖拽上传图片实例演示

前端  /  管理员 发布于 6年前   265

因为标题写的是实例,所以本次就不做讲解了,因为这个实例我也算是东拼西凑整出来的,参考了大概5、6款拖拽上传的插件和demo,然后把其中好的地方挑出来,最后就成了这么一个实例,一起来看下吧(地址不能保证长久有效,如果失效请在文章最后点击demo下载):
 
界面样式我是参考了一个国外的相册网站,改动不大,只是把鸟语转换成中文,以及上传时的样式也进行了改动,之所以选这个的原因就是,我很容易做扩展,它支持3种方式添加图片,一种拖拽上传,一种常规的选择文件上传,另外的就是添加网络图片。它很巧妙的把三种上传模式整合到了一起,而且你可以用IE浏览器浏览下,如果不支持HTML5,是没有拖拽上传图片的提示的,如图:
 
拖拽上传最重要的就是js部分的代码,它实现了70%的功能,另外30%仅仅是把图片信息提交到后台,然后做对应的处理,比如压缩啊,裁剪啊云云。所以先来看下js实现代码吧。

复制代码代码如下:
$().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();
}
});

开始我是先判断浏览器类型,因为刚才介绍过,不同浏览器看到的是不同界面。主要实现代码是从“功能实现”开始的,这块具体为何这样操作,原理是什么,我就不多说了,大家可以参考下这篇文章:《人人网首页拖拽上传详解(HTML5 Drag&Drop、FileReader API、formdata)》,不过ajax上传部分的代码还是有点不一样的,因为人人那个似乎有点麻烦,我就另寻途径了。
  最后就是上传部分的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="https:/html5/' . $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);
}
}

PHP最终会返回一个JSON格式的数组,我返回的信息就是图片地址、名称,还有段img的html代码,最后在js那边获取到json数组并处理,至此,操作结束。
文章最开始提到,还有点击选择文件上传和网络图片,因为这2个不属于这次的主题范围内,就不说了。况且这2个功能实现起来都不麻烦。
demo下载


  • 上一条:
    vscode可以运行c语言吗
    下一条:
    借助RubyGnome2库进行GTK下的Ruby GUI编程的基本方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 使用 Alpine.js 排序插件对元素进行排序(0个评论)
    • 在js中使用jszip + file-saver实现批量下载OSS文件功能示例(0个评论)
    • 在vue中实现父页面按钮显示子组件中的el-dialog效果(0个评论)
    • 使用mock-server实现模拟接口对接流程步骤(0个评论)
    • vue项目打包程序实现把项目打包成一个exe可执行程序(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-03
    • 2018-04
    • 2018-05
    • 2018-06
    • 2018-09
    • 2018-11
    • 2018-12
    • 2019-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2021-04
    • 2021-05
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客