html5+php implementation file Drag upload function

Source: Internet
Author: User
Tags file upload mkdir php file sha1 tld

Interface style I was referring to a foreign album website, change is not big, just convert the birds into Chinese, and upload the style also made changes, the reason for this choice is that I am easy to do extension, it supports 3 ways to add pictures, a drag and drop upload, a general selection file upload, The other is to add network pictures. It is very clever to integrate three kinds of upload mode, and you can use IE browser, if you do not support HTML5, is not dragging the upload picture prompts, as shown:

Drag and drop upload the most important is the JS part of the code, it achieved 70% of the function, the other 30% is only the picture information submitted to the background, and then do the corresponding processing, such as compression ah, cut ah so. So first look at the JS implementation code.

The code is as follows Copy Code

<! DOCTYPE html>
<meta charset= "Utf-8" >
<title> Untitled Document </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);
});
function realization
$ (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 ();
Get file List
var filelist = e.datatransfer.files;
var img = document.createelement (' img ');
Detects whether dragging files to a page is done
if (Filelist.length = = 0) {
$ ('. Dashboard_target_box '). Removeclass (' over ');
Return
}
Test file is not a picture
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{
Instantiating a file Reader object
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>

<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" > Choose your picture <br> start uploading </p>
<p id= "DTB-MSG1" class= "Dashboard_target_box_message" style= "top:-44px" >
<span class= "compatible" style= "display:inline" > Drag pictures to </span><span class= "Notcompatible" Display:none "> Dot </span> here <br> start uploading pictures
</p>
</div>
<p id= "DTB-MSG3" class= "dashboard_target_box_message" > Choose network Picture </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>


test.php file

The code is as follows Copy Code

<?php
$r = new StdClass ();
Header (' Content-type:application/json ');
$maxsize = 10; Mb
if ($_files[' xfile '] [' Size '] > ($maxsize * 1048576)) {
$r->error = "picture size" > picture size not exceeding $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 = '
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);
}
}
?>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.