701 字
4 分鐘
URL.revokeObjectURL 何時呼叫?圖片預覽換檔與移除時機
本文目錄
用 URL.createObjectURL(file) 做圖片預覽時,讓網址跟著預覽活到換檔、清除或移除元件為止。只要預覽仍提供另開或另存,就先保留目前的 blob: URL。切到新圖後撤銷舊網址,清除元件時撤銷最後一個。
圖片出現在畫面上,只代表這次圖片載入成功。依照 File API,撤銷前已經開始的請求仍可完成,之後重新讀取同一個網址則會得到網路錯誤。把清理綁在圖片的 load 事件上,畫面可能照樣顯示,使用者稍後點開原圖時才發現連結失效。
讓預覽元件持有目前那一個網址
把下面存成 HTML。重新選圖時,同步更新 img 和「另開原圖」的連結,再撤銷前一個網址。取消檔案選擇就維持原圖。
<!doctype html><html lang="zh-TW"><meta charset="utf-8"><title>本機圖片預覽</title><section id="picker"> <label>選擇圖片 <input type="file" accept="image/*"></label> <button type="button" id="clear">清除預覽</button> <p> <img id="preview" alt="選取圖片的預覽" width="240" hidden> <a id="original" target="_blank" rel="noopener" hidden>另開原圖</a> </p></section><button type="button" id="remove">移除預覽元件</button><script> const picker = document.querySelector('#picker'); const input = picker.querySelector('input'); const image = picker.querySelector('#preview'); const original = picker.querySelector('#original'); let currentUrl = null;
function showFile(file) { const previousUrl = currentUrl; currentUrl = file ? URL.createObjectURL(file) : null;
if (currentUrl) { image.src = currentUrl; original.href = currentUrl; } else { image.removeAttribute('src'); original.removeAttribute('href'); }
image.hidden = original.hidden = currentUrl === null; if (previousUrl !== null) URL.revokeObjectURL(previousUrl); }
input.addEventListener('change', () => { const file = input.files[0]; if (file) showFile(file); });
picker.querySelector('#clear').addEventListener('click', () => { input.value = ''; showFile(null); });
document.querySelector('#remove').addEventListener('click', () => { showFile(null); picker.remove(); }, { once: true });</script></html>同一個 File 呼叫兩次 createObjectURL() 會得到兩個獨立網址。若畫面有多張可同時保留的縮圖,讓每張縮圖各自管理自己的網址,並在移除該張時清理。這個範例假設圖片只由這個元件使用。若另一個元件也共用原圖連結,就把清理移到能判斷最後一個使用者已離開的地方。
在 Console 分辨太早撤銷和忘記撤銷
- 選第一張圖片,執行
const firstUrl = document.querySelector('#preview').src。接著執行(await fetch(firstUrl)).ok,結果應為true。 - 選第二張圖,再讀一次
#preview的src。新網址應可讀取,重新執行fetch(firstUrl)應得到網路錯誤。 - 把第二張的網址存成變數,再按「清除預覽」。第二張的網址也應失效。另選一張後按「移除預覽元件」,可用同一方法確認卸載清理。
這組檢查可以驗證網址是否還能讀取。瀏覽器何時回收已解碼的影像或釋放其他引用,還取決於目前使用狀態。提交表單時,可以把原本的 File 放進 FormData,預覽用的 blob: URL 只在瀏覽器裡使用。
參考資料:
URL.revokeObjectURL 何時呼叫?圖片預覽換檔與移除時機
https://laplusda.com/posts/javascript-revoke-object-url-image-preview/