Html5 drag/drop upload image example

Source: Internet
Author: User
Tags tld

Comments: 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, for more information about cropping and cloud, please refer to the following. I hope you will not explain this because the title is an instance, this is because I have integrated this instance. I have referenced about 5 and 6 drag-and-drop upload plug-ins and Demos, picked out the good ones, and finally became such an instance, let's take a look (the address cannot be guaranteed to be valid for a long time. If it becomes invalid, click the demo to download it at the end of the article ):
 
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:
$ (). 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 ();
}
});

In the beginning, I first judge the browser type, because different browsers see different interfaces. The main implementation code starts with "function implementation". I will not talk about the specific reason for this operation and the principle. You can refer to the following article: details on Drag and Drop upload on Renren homepage (HTML5 Drag & Drop, FileReader API, and formdata). However, the code for uploading ajax files is still a bit different, because Renren seems a little troublesome, I will find another way.
The last step is to upload some PHP code. Here I just provide a reference. You can compile it as needed.

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

PHP will eventually return an array in JSON format. The information I return is the image address, name, and img html code. Finally, the json array is obtained and processed in js. At this point, the operation is complete.
As mentioned at the beginning of this article, we also click to select File Upload and network images, because these two are not within the scope of this topic, so we won't talk about them. Besides, these two functions are easy to implement.
Download demo

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.