FileReader readAsDataURL Previews Images

readAsDataURL turns a picked image file into a data: URL string, giving an img preview without any object URL that must be revoked.

JavascriptFile Upload

Code

javascriptsnippet
21 lines
const input = document.querySelector('input[type="file"]');
const preview = document.querySelector('#preview');

input.addEventListener('change', () => {
  const file = input.files?.[0];
  if (!file || !file.type.startsWith('image/')) {
    console.log('not an image file');
    return;
  }

  // FileReader.readAsDataURL turns the file into a data: URL, so there is
  // no object URL to revoke afterwards
  const reader = new FileReader();
  reader.onload = () => {
    const dataUrl = String(reader.result);
    console.log('data URL head:', dataUrl.slice(0, 29));
    preview.src = dataUrl;
  };
  reader.onerror = () => console.log('read error:', reader.error?.message);
  reader.readAsDataURL(file);
});

Inside the snippet

Demo state sits in top-level bindings: input, preview.

Caveats

  • No third-party code is loaded at any point while this runs.
  • A browser is the runtime here: document are not available in Node.

Using it

Output lines are prefixed (not an image file, data URL head:, read error:), so each step’s effect shows up clearly in the output.

Key statements worth quoting

const file = input.files?.[0];
reader.onload = () => {
  const dataUrl = String(reader.result);
  console.log('data URL head:', dataUrl.slice(0, 29));
  preview.src = dataUrl;
};

Interactive Tools for This Topic

FAQ

Does FileReader readAsDataURL Previews Images run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.