Html5 + php implements the file drag upload function,

Source: Internet
Author: User
Tags tld

Html5 + php implements the file drag upload function,

I have referenced a foreign album website for the interface style, but it has not changed much. I just converted the bird language into Chinese and the style during upload. The reason for this is that, I can easily scale it. It supports three ways to add images, one is drag and drop upload, the other is to select a file to upload, and the other is to add a network image. It skillfully integrates the three upload modes, and you can use the IE browser to browse. If HTML5 is not supported, there is no prompt to drag and drop to upload images,

 

The most important part of drag-and-drop upload is the js Code, which implements 70% of the functions. The other 30% only submits the image information to the background and then processes the image, such as compression, crop the cloud. So let's take a look at the js implementation code.

The Code is as follows:
<! Doctype html>
<Html>
<Head>
<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 implementation
$ (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 ();
// Obtain the file list
Var fileList = e. dataTransfer. files;
Var img = document. createElement ('img ');
// Check whether the operation is performed by dragging a file to the page.
If (fileList. length = 0 ){
$ ('. Dashboard_target_box'). removeClass ('over ');
Return;
}
// Check whether the file is an image.
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 {
// Instantiate the 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" Maid ({width: '0px '});
Certificate ('.show'{.html ('');
If (e. lengthComputable ){
Var loaded = Math. ceil (e. loaded/e. total) * 100 );
$ ("# Dtb-msg4" Maid ({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.tar get. 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"> select your image <br> Start upload </p>
<P id = "dtb-msg1" class = "dashboard_target_box_message" style = "top:-44px">
<Span class = "compatible" style = "display: inline"> drag an image to </span> <span class = "notcompatible" style = "display: none "> click </span> here <br> start uploading images.
</P>
</Div>
<P id = "dtb-msg3" class = "dashboard_target_box_me (www.111cn.net) ssage"> select a network image </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 file

The Code is as follows:
<? Php
$ R = new stdClass ();
Header ('content-type: application/json ');
$ Maxsize = 10; // Mb
If ($ _ FILES ['xfile'] ['SIZE']> ($ maxsize * 1048576 )){
$ R-> error = "image size"> the image size cannot exceed $ 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 );
}
}
?>

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




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.