Principle and Example of Pasting and Uploading Pictures by Js

  • 2021-10-13 06:04:00
  • OfStack

We have used various rich text editors more or less, and one of them is a very convenient function. Copy a picture and paste it into a text box, and this picture will be uploaded. So how does this convenient function come true?

Principle analysis:
Copy = > Paste = > Upload

In this process, what we need to do is: listen for paste events = > Get the contents of the clipboard = > Send a request to upload

What needs to be understood is:

We can only upload the pictures taken by the screenshot tool (qq screenshots, WeChat screenshots, etc.), but can't paste the pictures in the upload system (copied from the desktop and hard disk), because they exist in completely different places.

Aware of the paste event event: When you paste (right-click paste/ctrl+v), this action triggers a clipboard event called 'paste', which is triggered before the data in the clipboard is inserted into the target element. If the target element (where the cursor is located) is editable (div with contenteditable. textarea does not work), the paste action will insert the data in the clipboard into the target element in the most appropriate format; If the target element is not editable, no data is inserted, but paste event is fired. Data is read-only during pasting.

After listening to the paste event and knowing the manifestation, the next step is how to get the data:

chrome has a specific method, base64 encoded strings of pictures in the clipboard (whether pasted by screenshots or copied and pasted by web pages) can be obtained by api such as clipboardData. items, getAsFile (), new FileReader (), etc. There is no such api in ie11 and firefox, but there is still a way to obtain it, because the data has been displayed in src of img. For screenshots pasted, take the src attribute value of img directly (base64), and for web pages pasted, send the address to the background, and then according to the address down, there is its own server, and finally return the new address to the front end for display. In order to keep the uniformity easy to manage, Unification 1 replaces the src attribute of img in all cases (screenshots, web pages) with its own stored address.

Full example:


<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Js Paste and upload pictures </title>
    <script src="jquery.js"></script>
</head>

<body>
     Copy, paste and upload pictures: 
    <div id="content_img" contentEditable="true" style="width:500px;height:500px;border:1px solid #000;"></div>
    <script>
        document.getElementById('content_img').addEventListener('paste', function(e) {
        if (!(e.clipboardData && e.clipboardData.items)) {
            return;
        }
        for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
            var item = e.clipboardData.items[i];
            if (item.kind === "string") {
                item.getAsString(function(str) {
                    console.log(str);
                    alert(" Please paste the picture and upload it ");
                })
                $("#content_img").html(""); 
            } else if (item.kind === "file") {
                var blob = item.getAsFile();
                console.log(blob);
                if (blob.size === 0) {
                    return;
                }
                var data = new FormData();
                data.append("image", blob);
                $.ajax({
                    url: "http://www.yzmcms.com/upload.php",
                    type: 'POST',
                    cache: false,
                    data: data,
                    processData: false,
                    contentType: false,
                    dataType: "json", 
                    success: function(result) {
                        console.log(result);
                        if (result.status) {
                            var html = "<img src=" + result.data + " width='100' height='100'>";
                            $("#content_img").append(html);
                        } else {
                            console.log(result.message)
                        }
                    }
                });

                // Block the default behavior, that is, prevent clipboard contents from being stored in the div Displayed in the 
                e.preventDefault();
            }
        }
    });
    </script>
</body>

</html>

The above is the Js paste upload picture principle and examples of detailed content, more about JS paste upload picture information please pay attention to other related articles on this site!


Related articles: