PHP to implement paste screenshots and complete upload function

Source: Internet
Author: User
Tags md5

Today found Segmentfault comments inside can paste upload pictures, so the study of how to achieve!

The principle is very simple is to monitor the paste event, and then detect whether the pasted things inside there are pictures, and some words directly triggered Ajax upload

Code can be run directly, interested you can try

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The <?php header ("access-control-allow-origin:*"); $url = ' http://'. $_server[' Http_host ']; $file = (isset ($_post["file"))? $_post["File"]: '; if ($file) {$data = Base64_decode (Str_replace (' data:image/png;base64, ', ', ', $file));//screenshots can only be a PNG format picture, so just deal with PNG on the line $ NAME = MD5 (time ()). '. png '; Here the filename is done MD5 processing file_put_contents ($name, $data); echo "$url/$name"; Die }?>     <div id= "box" style= "width:400px;height:400px;border:1px solid;" contenteditable> </div> <input type= "hidden" name= "img" value= "" id= "Img_puth"/>   <script>/ /Find the box element to detect when pasting, document.queryselector (' #box '). AddEventListener (' Paste ', function (e) { //determine if it is pasted picture if ( E.clipboarddata && E.clipboarddata.items[0].tyPe.indexof (' image ') >-1 {var = this, reader = new FileReader (); file = E.clipboarddata.items[0].getasfile (); &n Bsp Ajax upload Picture Reader.onload = function (e) {var xhr = new XMLHttpRequest (), FD = new FormData ()   Xhr.open (' POST ', ', ', true); Xhr.onload = function () {var img = new Image (); img.src = Xhr.responsetext;  //that.innerhtml = ' '; Xhr.send (FD); } reader.readasdataurl (file); }}, False); </script>

The above is the entire contents of this article, I hope you can enjoy.

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.