The reason why "screenshot" needs to be quoted is that "screenshot" cannot be implemented, but we can use different methods, such as short chat software, QQ, and trademanager, after screenshots of these software are taken, the data will be saved as a copy in the "clipboard". Here we mainly talk about how to obtain the images uploaded from the "clipboard" and display them on the webpage. For the web, when users mention this requirement, our initial ideas may be: Unless embedded controls are developed, they cannot be implemented at all.
However, with the rise of webkit and other kernel browsers, we can use W3C APIs and some flexible methods to implement this function.
Today we will talk about how to implement "screenshot" and upload in web pages.
The reason why "screenshot" needs to be quoted is that "screenshot" cannot be implemented, but we can use different methods, such as short chat software, QQ, and trademanager, after screenshots of these software are taken, the data will be saved as a copy in the "clipboard". Here we mainly talk about how to obtain the images uploaded from the "clipboard" and display them on the webpage.
We need to use the following two functions:
Clipboard API and eventsThis document describes APIs for clipboard operations such as copy, cut and paste in web applications. file APIThis specification provides an API for representing file objects in web applications, as well as programmatically selecting them and accessing their data. with these materials, the implementation is also so easy !!
Save the following code as an html page, use QQ or trademanager to cut a picture, and return to the page. ctrl + v, you will find that Something amazing has happened.
// For security reasons, the browser provides us with an onpaste event. Reading Clipboard data can only be performed in the event handler when this event occurs.
| The Code is as follows: |
Copy code |
Document. body. onpaste = function (e ){ // Console. log (e) Var items = e. clipboardData. items; For (var I = 0; I <items. length; ++ I ){ Var item = e. clipboardData. items [I]; If (items [I]. kind = 'file' & items [I]. type = 'image/png '){ // For more information about FileReader, see API Var fileReader = new FileReader (); // ReadAsDataURL is an asynchronous process. The callback method is provided here. FileReader. onloadend = function (){ Var d = this. result. substr (this. result. indexOf (',') + 1 ); Var img = document. createElement ("img "); Img. src = "data: image/jpeg; base64," + d; Document. body. appendChild (img ); }; // DataURL. If you are not clear about it, you can check the information. FileReader. readAsDataURL (item. getAsFile ()); Break; // Just get one } } }; |
To upload data, save the DataURL to the form and submit the data asynchronously.
The backend server converts a DataURL to an image and returns the physical path
In this way, a complete "screenshot" function for uploading images on a webpage is achieved.