1

I want to add an input box (a placeholder) where the user could paste a screenshot into. img is not going to do it as it requires the screenshot to be saved into an image file, then the scr be directed to it. Too cumbersome. I want a simple copy (or print screen) and paste to do it.

I modified the code from the following discussion: HTML Paste Clipboard Image to File Input, but it does not work.

<form id="new_document_attachment" method="post">
        <div class="actions"><input type="submit" name="commit" value="Submit" /></div>
        <img src="" alt="Screen Shot" id="image_attachment_doc">
</form>
<script>
    const form = document.getElementById("new_document_attachment");
    const imageInput = document.getElementById("image_attachment_doc");

    imageInput.addEventListener('change', () => {
    form.submit();
    });

    window.addEventListener('paste', e => {
    imageInput.src = e.clipboardData.files;});
</script>
Kambiz
  • 221
  • 1
  • 3
  • 15
  • Does this answer your question? [HTML Paste Clipboard Image to File Input](https://stackoverflow.com/questions/50427513/html-paste-clipboard-image-to-file-input) – alexyorke Dec 07 '19 at 21:27
  • I did use the code on this page. It still requires attaching a picture file, and not really 'pasting' from the clipboard image. – Kambiz Dec 07 '19 at 22:47
  • I actually modified the code as below, and it still does not work: – Kambiz Dec 07 '19 at 23:05
  • The problem is that the `imageInput.src` holds a string, when you assing it the File object it becomes serialized into the string `"[Object File]"` – hultqvist Aug 15 '20 at 06:51

1 Answers1

0

You need to convert the image data in the File object into a Data URL.
Thanks to Loading an image to a <img> from <input file>

Your example is also a bit limited in that although the image would show up, the page would reload almost immediately.

In the example below the form is not submitted.

const log = document.getElementById("log");

window.addEventListener('paste', e => {
  var files = e.clipboardData.files;
  
  //Put the file into an input so it will be included with the form submit
  document.getElementById("files").files = files;
  
  //This won't work because the src holds a string
  //and the file object becomes serialized into "[object%20File]"
  //This can be seen in the console
  document.getElementById("img").src = files[0];
  
  //Show image by loading it as an DataURL
  var fr = new FileReader();
  fr.onload = function() {
    document.getElementById("img").src = fr.result;
  }
  fr.readAsDataURL(files[0]);
});
<form id="form" method="post">
  <img id="img" alt="Screen Shot">
  <input type="file" name="files" id="files" />
  <input type="submit" />
</form>

<p>Press Ctrl+V to paste an image into this window</p>
hultqvist
  • 14,837
  • 14
  • 59
  • 90