1

I made a javascript tool which converts images into base64 tags:

function readFile() {
  
  if (this.files && this.files[0]) {
    
    var FR= new FileReader();
    
    FR.addEventListener("load", function(e) {
      document.getElementById("img").src = e.target.result;
      document.getElementById("b64").innerHTML = e.target.result;
    }); 
    
    FR.readAsDataURL( this.files[0] );
  }
  
}

window.addEventListener('paste', e => {
  document.getElementById("inp").files = e.clipboardData.files;
});

document.getElementById("inp").addEventListener("change", readFile);


function copyData() {
          var copyText = document.getElementById("b64");
          copyText.select();
          copyText.setSelectionRange(0, 9999999999)
          document.execCommand("copy");
}

function generateTag() {
document.getElementById("tag").innerHTML = "<img src='" + document.getElementById('b64').value + "'/>";
}

function copyTag() {
          var copyText = document.getElementById("tag");
          copyText.select();
          copyText.setSelectionRange(0, 9999999999)
          document.execCommand("copy");
}

and the html body:

<input id="inp" type='file'><br>
<button onclick="copyData()">Copy data</button>
<button onclick="generateTag(); copyTag()">Generate image tag and copy</button>
<br>

<textarea readonly placeholder="Base64 data" id="b64" rows="6"></textarea>

<textarea readonly placeholder="HTML image tag" id="tag" rows="6"></textarea>

<img id="img">

There is a problem, reading and converting images to code by clicking Select file works fine, but through function copyData() pasting a copied image from clipboard can be read, but it does not get converted. How can I fix this?

jack
  • 305
  • 1
  • 8
  • 1
    Not sure if I understand but you can't paste stuff into file input. Maybe you should describe what you want to achieve by this tool? – m.cichacz Oct 01 '20 at 15:25

1 Answers1

1

I'm not sure it will works on all browser but you can access clipboard data like this:

window.addEventListener('paste', e => {
  console.log(e.clipboardData.getData('Text'));
  var copiedData = e.clipboardData.getData('Text');
  // Now you can use base64 data
});

Take a look at this topic too: Get current clipboard content?

mihnsen
  • 385
  • 3
  • 8