Php implements the paste and upload function, and php pastes and uploads. Php implements the paste and upload function. php pasted and uploaded. Today, we found that segmentfault's comments can be pasted into the uploaded image. so we studied how to achieve this! The principle is very simple. php implements the upload and pasting function. php uploads and pasting.
Today, I found that segmentfault's comment can be pasted and uploaded, so I studied how to implement it!
The principle is very simple. In fact, it is to monitor and paste events, and then check whether there are images in the pasted items. if so, ajax upload is directly triggered.
Code can be run directly. if you are interested, try it.
<? Phpheader ("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); // only images in png format can be obtained. Therefore, you only need to process png. $ name = md5 (time ()). '.png '; // the file name is md5 processed here. file_put_contents ($ name, $ data); echo "$ url/$ name"; die ;}?>Script // search for the box element to check the document. querySelector ('# box '). addEventListener ('paste ', function (e) {// Determine whether the image is pasted if (e. clipboardData & e. clipboardData. items [0]. type. indexOf ('image')>-1) {var that = this, reader = new FileReader (); file = e. clipboardData. items [0]. getAsFile (); // ajax uploads an image 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 = ''; document. getElementById ("img_puth "). value = img. src;} // this. result to get the base64 (which can be used for instant display) fd of the image. append ('file', this. result); that. innerHTML = ''; xhr. send (fd);} reader. readAsDataURL (file) ;}}, false); script
The above is all the content of this article. I hope you will like it.
Today, I found that segmentfault's comment can be pasted and uploaded, so I studied how to implement it! The principle is very simple...