Data URLs from PNGs and stuf

I sometimes need this.

Pasting an image onto page should work?

Or choose a file. Dragging and dropping onto the file input thing appears to work:


const input = document.querySelector("#file");
const lastli = document.querySelector("#lastli");

const addLink = (text, href) => {
  const li = document.createElement("li");
  const a = li.appendChild(document.createElement("a"));
  a.innerText = text;
  a.href = href;
  lastli.before(li);
};

document.onpaste = e => {
  for (const item of e.clipboardData.items) {
    if (item.kind === 'file') {
      const blob = item.getAsFile();
      const fr = new FileReader();
      fr.onload = ev => addLink(item.type, ev.target.result);
      fr.readAsDataURL(blob);
    }
  }
};

input.onchange = () => {
  for (const file of input.files) {
    const fr = new FileReader();
    fr.onload = () => addLink(file.name, fr.result);
    fr.readAsDataURL(file);
  }
};