HTML5 drag and drop upload image instances

Source: Internet
Author: User
Tags tld

Because the title is written into an instance, I will not explain it this time, because this instance is also made up by us. I have referenced about 5 and 6 plug-ins and demos for drag-and-drop upload, then pick out the good place, and finally become such an instance, let's take a look at it together (the address cannot guarantee long-term effectiveness, if the failure please click at the end of the article demo download): http://hoorayos.caifutang.com/dropupload.html

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.

$ (). 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 (); // get the file list var fileList = e. dataTransfer. files; var img = document. createElement ('img '); // check whether the operation is performed to drag a file to the page if (fileList. length = 0) {$ ('. dashboard_target_box '). removeClass ('over'); return;} // checks 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" ).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.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.

$ R = new stdClass (); header ('content-type: application/json'); $ maxsize = 10; // Mbif ($ _ 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_nam E "], $ 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, 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

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.