brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: URL.createObjectURL previews a chosen photo before any web upload

Web
~/tips/tip-web-createobjecturl-photo-preview

url = URL.createObjectURL(file);

Show the picked image at once, without sending it to a server first.

People like to see that they picked the right picture before they press Send. You can show it instantly, and nothing has to leave their device for that.

<input type="file" id="pick" accept="image/*">
<img id="preview" alt="Preview of your photo" width="300">
<script>
  let url;
  pick.addEventListener('change', () => {
    if (url) URL.revokeObjectURL(url);
    const file = pick.files[0];
    if (!file) return;
    url = URL.createObjectURL(file);
    preview.src = url;
  });
</script>

The function returns a short blob: address that points at the file in memory. It is immediate, even for a big photo, because nothing is converted into a long text string.

The revokeObjectURL line frees the previous one. Without it every new choice keeps another copy around until the page closes.

I would not trust the preview as validation. accept is a hint to the file picker, and a user can still choose something else, so your server has to check the upload itself. Some image formats that a phone produces may also fail to display in some browsers even though the upload would work.

Further reading: MDN: URL.createObjectURL()

More Web tips async function sha256(text) { function setFilter(name, value) { and open <span translate="no">Home Assistant</span> in your browser. …the page behind the drawer… inputmode="numeric" autocomplete="one-time-code"> All Web tips (6) All topics

Link