How to upload an image using the clipboard API

Written by Richard, on 19th September 2022

For me, this is a holy-grail type thing! Uploading images to websites is a bit of a faff if you ask me - first copy the image to the clipboard (no problems there - just press PrtScr to take a screenshot) but then you have to save the image to a file - and this involves opening up a paint program (eg MSPaint, Paint Shop Pro or Photoshop); pasting the image into it; save it to a file and finally you have a file which you can upload to the website using the standard file upload control.

Well this is an example of a page that reads the clipboard directly when uploading an image so that all you now have to do is press PrtScr to grab a screenshot and paste it into the webpage. Oh and press the submit button to submit the form...

The following code is a full, self-contained page so you can grab the code and paste it into a file on your server and it should work. All it does is allow you to paste an image onto the page and then upload it. Once uploaded it will show you the resulting data.

The idea for this code came from a jsFiddle snippet by someone called Nick. There's a live demo of this code here:

https://www.rgraph.net/blog/2022/clipboard-file-upload.php

<?php
    if (!empty($_POST)) {

        // Handle the POSTed data here - the image is actually base64 encoded data in
        // the $_POST['myTextarea'] variable which you can run through the base64_decode()
        // function and then write to a file

        $pos     = strpos($_POST['myTextarea'], 'base64,');     // Get the position of the string "base64,"
        $encoded = substr($_POST['myTextarea'], $pos + 7);      // Get the base64 data (which starts after the comma)
        $raw     = base64_decode($encoded);                        // Decode the base64 data into raw binary

        // Show the base64 encoded data - use the $raw variable when
        // writing the uploaded data to a file.
        //
        var_dump($_POST);
        exit;
    }
?>
<!DOCTYPE html >
<html>
<body>

<h1>File upload using paste</h1>

<p>
    You can paste an image, which is on your clipboard, into this window and it will appear below.
    If you use Windows you can press <b>PrtScr</b> to get a screenshot on your clipboard. Then
    press <b>CTRL+V</b> to paste it into this document.
</p>

<!-- P   -->
<form action="" method="post">
    <div id="form-elements-container">
        <input type="text" value="An example text input..." name="myTextInput"><br />
        <input type="submit" value="Submit form"><br />
    </div>
</form>

<!-- This is where the image thumbnail(s) will appear -->
<div id="images-container"></div>

<script>
    counter = 0;

    // All of this code runs when the image is pasted into the page
    // and the onpaste event fires.
    //
    document.body.onpaste = function (e)
    {
        var items = (e.clipboardData  || e.originalEvent.clipboardData).items;

        // Find the pasted image among the pasted items list. If the
        // type is not an image then its ignored.
        //
        var blob = null;
        for (var i=0; i<items.length; i++) {
            if (items[i].type.indexOf("image") === 0) {
                blob = items[i].getAsFile();
            }
        }

        // Load image if there is a pasted image. Testing the blob
        // variable tells us if there has been an image uploaded.
        //
        if (blob !== null) {

            var reader = new FileReader();

            reader.onload = function(e)
            {




                // Create a new image object from the pasted image.
                // The src attribute of the new <img> tag is set to
                // the data: URL of the new image
                //
                var img    = new Image();
                img.src    = e.target.result;
                img.width  = 128;
                img.height = 128;
                img.style.margin = '5px';




                // Append the file to the document. This causes the
                // uploaded image to appear on the page
                //
                document.getElementById('images-container').appendChild(img);




                // Add a new textarea to the form - this textarea
                // is used to show the data: URL of the image
                //
                var textarea    = document.createElement('textarea');
                textarea.name   = 'myTextarea_' + counter++;
                textarea.value  = img.src;
                textarea.style.width  = '128px';
                textarea.style.height = '200px';
                document.getElementById('form-elements-container').appendChild(textarea);

            };

            reader.readAsDataURL(blob);
        }
    }
</script>
</body>
</html>