HTML5经典应用:拖拽上传图片

操作方法

  • 01

    因为标题写的是实例,所以本次就不做讲解了,因为这个实例我也算是东拼西凑整出来的,参考了大概5、6款拖拽上传的插件和demo,然后把其中好的地方挑出来,最后就成了这么一个实例,一起来看下吧。 界面样式我是参考了一个国外的相册网站,改动不大,只是把鸟语转换成中文,以及上传时的样式也进行了改动,之所以选这个的原因就是,我很容易做 扩展,它支持3种方式添加图片,一种拖拽上传,一种常规的选择文件上传,另外的就是添加网络图片。它很巧妙的把三种上传模式整合到了一起,而且你可以用 IE浏览器浏览下,如果不支持HTML5,是没有拖拽上传图片的提示的,如图:

  • 02

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

  • 03

    01$().ready(function(){ 02 if($.browser.safari || $.browser.mozilla){ 03 $('#dtb-msg1 .compatible').show(); 04 $('#dtb-msg1 .notcompatible').hide(); 05 $('#drop_zone_home').hover(function(){ 06 $(this).children('p').stop().animate({top:'0px'},200); 07 },function(){ 08 $(this).children('p').stop().animate({top:'-44px'},200); 09 }); 10 //功能实现 11 $(document).on({ 12 dragleave:function(e){ 13 e.preventDefault(); 14 $('.dashboard_target_box').removeClass('over'); 15 }, 16 drop:function(e){ 17 e.preventDefault(); 18 //$('.dashboard_target_box').removeClass('over'); 19 }, 20 dragenter:function(e){ 21 e.preventDefault(); 22 $('.dashboard_target_box').addClass('over'); 23 }, 24 dragover:function(e){ 25 e.preventDefault(); 26 $('.dashboard_target_box').addClass('over'); 27 } 28 }); 29 var box = document.getElementById('target_box'); 30 box.addEventListener("drop",function(e){ 31 e.preventDefault(); 32 //获取文件列表 33 var fileList = e.dataTransfer.files; 34 var img = document.createElement('img'); 35 //检测是否是拖拽文件到页面的操作 36 if(fileList.length == 0){ 37 $('.dashboard_target_box').removeClass('over'); 38 return; 39 } 40 //检测文件是不是图片 41 if(fileList[0].type.indexOf('image') === -1){ 42 $('.dashboard_target_box').removeClass('over'); 43 return; 44 } 45 46 if($.browser.safari){ 47 //Chrome8+ 48 img.src = window.webkitURL.createObjectURL(fileList[0]); 49 }else if($.browser.mozilla){ 50 //FF4+ 51 img.src = window.URL.createObjectURL(fileList[0]); 52 }else{ 53 //实例化file reader对象 54 var reader = new FileReader(); 55 reader.onload = function(e){ 56 img.src = this.result; 57 $(document.body).appendChild(img); 58 } 59 reader.readAsDataURL(fileList[0]); 60 } 61 var xhr = new XMLHttpRequest(); 62 xhr.open("post", "test.php", true); 63 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 64 xhr.upload.addEventListener("progress", function(e){ 65 $("#dtb-msg3").hide(); 66 $("#dtb-msg4 span").show(); 67 $("#dtb-msg4").children('span').eq(1).css({width:'0px'}); 68 $('.show').html(''); 69 if(e.lengthComputable){ 70 var loaded = Math.ceil((e.loaded / e.total) * 100); 71 $("#dtb-msg4"). children('span').eq(1).css({width:(loaded*2)+'px'}); 72 } 73 }, false); 74 xhr.addEventListener("load", function(e){ 75 $('.dashboard_target_box').removeClass('over'); 76 $("#dtb-msg3").show(); 77 $("#dtb-msg4 span").hide(); 78 var result = jQuery.parseJSON(e.target.responseText); 79 alert(result.filename); 80 $('.show').append(result.img); 81 }, false); 82 83 var fd = new FormData(); 84 fd.append('xfile', fileList[0]); 85 xhr.send(fd); 86 },false); 87 }else{ 88 $('#dtb-msg1 .compatible').hide(); 89 $('#dtb-msg1 .notcompatible').show(); 90 } 91});

  • 04

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

  • 05

    最后就是上传部分的PHP代码了,这里我只是提供个参考,你可以根据项目的需求来自己编写。 001$r = new stdClass(); 002header('content-type: application/json'); 003$maxsize = 10; //Mb 004if($_FILES['xfile']['size'] > ($maxsize * 1048576)){ 005 $r->error = "图片大小不超过 $maxsize MB"; 006} 007$folder = 'files/'; 008if(!is_dir($folder)){ 009 mkdir($folder); 010} 011$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : ''; 012if(!is_dir($folder)){ 013 mkdir($folder); 014} 015 016if(preg_match('/image/i', $_FILES['xfile']['type'])){ 017 $filename = $_POST['value'] ? $_POST['value'] : $folder . sha1(@microtime() . '-'. $_FILES['xfile']['name']) . '.jpg'; 018}else{ 019 $tld = split(',', $_FILES['xfile']['name']); 020 $tld = $tld[count($tld) - 1]; 021 $filename = $_POST['value'] ? $_POST['value'] : $folder . sha1(@microtime() . '-'. $_FILES['xfile']['name']) . $tld; 022} 023 024$types = Array('image/png', 'image/gif', 'image/jpeg'); 025if(in_array($_FILES['xfile']['type'], $types)){ 026 $source = file_get_contents($_FILES["xfile"]["tmp_name"]); 027 imageresize($source, $filename, $_POST['width'], $_POST['height'], $_POST['crop'], $_POST['quality']); 028}else{ 029 move_uploaded_file($_FILES["xfile"]["tmp_name"], $filename); 030} 031 032$path = str_replace('test.php', '', $_SERVER['SCRIPT_NAME']); 033 034$r->filename = $filename; 035$r->path = $path; 036$r->img = '<img src="' . $path . $filename . '" alt="image" />'; 037 038echo json_encode($r); 039 040functionimageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) { 041 $quality = $quality ? $quality : 80; 042 $image = imagecreatefromstring($source); 043 if ($image) { 044 // Get dimensions 045 $w = imagesx($image); 046 $h = imagesy($image); 047 if (($width && $w > $width) || ($height && $h > $height)) { 048 $ratio = $w / $h; 049 if (($ratio >= 1 || $height == 0) && $width && !$crop) { 050 $new_height = $width / $ratio; 051 $new_width = $width; 052 } elseif ($crop && $ratio <= ($width / $height)) { 053 $new_height = $width / $ratio; 054 $new_width = $width; 055 } else { 056 $new_width = $height * $ratio; 057 $new_height = $height; 058 } 059 } else { 060 $new_width = $w; 061 $new_height = $h; 062 } 063 $x_mid = $new_width * .5; //horizontal middle 064 $y_mid = $new_height * .5; //vertical middle 065 // Resample 066 error_log('height: ' . $new_height . ' - width: ' . $new_width); 067 $new = imagecreatetruecolor(round($new_width), round($new_height)); 068 imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h); 069 // Crop 070 if ($crop) { 071 $crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height); 072 imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height); 073 //($y_mid - ($height * .5)) 074 } 075 // Output 076 // Enable interlancing [for progressive JPEG] 077 imageinterlace($crop ? $crop : $new, true); 078 079 $dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION)); 080 if ($dext == '') { 081 $dext = $ext; 082 $destination .= '.' . $ext; 083 } 084 switch ($dext) { 085 case 'jpeg': 086 case 'jpg': 087 imagejpeg($crop ? $crop : $new, $destination, $quality); 088 break; 089 case 'png': 090 $pngQuality = ($quality - 100) / 11.111111; 091 $pngQuality = round(abs($pngQuality)); 092 imagepng($crop ? $crop : $new, $destination, $pngQuality); 093 break; 094 case 'gif': 095 imagegif($crop ? $crop : $new, $destination); 096 break; 097 } 098 @imagedestroy($image); 099 @imagedestroy($new); 100 @imagedestroy($crop); 101 } 102}

  • 06

    PHP最终会返回一个JSON格式的数组,我返回的信息就是图片地址、名称,还有段img的html代码,最后在js那边获取到json数组并处理,至此,操作结束。

  • 07

    文章最开始提到,还有点击选择文件上传和网络图片,因为这2个不属于这次的主题范围内,就不说了。况且这2个功能实现起来都不麻烦。

(0)

相关推荐

  • 快速清理桌面:逗游教您一键拖拽

    曾经有一次清理电脑桌面的机会摆在我面前,我没有珍惜,当我桌面变得杂乱无章的时候才后悔莫及,人生最痛苦的事莫过于删除、卸载、整理、杀毒最终导致删错东西导致崩溃重装系统。如果上天在给我一次机会的话,我会下 ...

  • 酷我音乐桌面歌词是能够拖拽吗 如何调节大小?

    首先如果您锁定了桌面歌词的话,需要解锁桌面歌词,可以在托盘菜单中选择“解锁桌面歌词” 然后您可以将鼠标移至桌面歌词的文字上,这将激活桌面歌词的菜单栏,然后鼠标点击菜单栏,就可以将桌面歌词拖拽到您所需的 ...

  • BlueStacks安卓模拟器不能调整屏幕窗口大小用鼠标拖拽也不能

    使用过BlueStacks安卓模拟器的朋友都知道,这款安卓模拟器非常好用,占用资源很少,但是有个缺点是占屏很大,首次安装后在我电脑24寸显示器1680*1050像素的分辨率上面感觉都是满屏的感觉,非常 ...

  • 鼠标拖拽失灵解决办法

    鼠标拖拽失灵解决办法:快速按两下ESC

  • 优酷客户端如何拖拽视频进行播放?

    您可以拖拽详情界面、频道界面、推荐界面、播放记录页面的单集视频海报至播放页面进行播放,同时也可以将本地*.kux及*.flv文件直接拖拽到播放界面上进行播放哦。 温馨提示:暂不支持专辑视频拖拽播放,如 ...

  • 世界之窗浏览器如何使用超级拖拽

    拖拽链接、图片或者选中的文字等在页面上其他地方放开(即超级拖拽),即可在新标签中打开对应的链接、图片或搜索选中的文字。熟练使用超级拖拽功能可以大大改善您的浏览体验,提高您的浏览速度。 在 选项→高级→ ...

  • 360安全浏览器6.0超级拖拽设置

    拖拽链接、图片或者选中的文字等在页面上其他地方放开(即超级拖拽),即可在新标签中打开对应的链接、图片或搜索选中的文字。熟练使用超级拖拽功能可以大大改善您的浏览体验,提高您的浏览速度。

  • 酷我音乐桌面歌词是否能够拖拽如何调节大小?

    首先如果您锁定了桌面歌词的话,需要解锁桌面歌词,可以在托盘菜单中选择“解锁桌面歌词” 然后您可以将鼠标移至桌面歌词的文字上,这将激活桌面歌词的菜单栏,然后鼠标点击菜单栏,就可以将桌面歌词拖拽到您所需的 ...

  • 360极速浏览器的超级拖拽

    拖拽链接、图片或者选中的文字等在页面上其他地方放开(即超级拖拽),即可在新标签中打开对应的链接、图片或搜索选中的文字。熟练使用超级拖拽功能可以大大改善您的浏览体验,提高您的浏览速度。