使用 URL.createObjectURL 的方法上傳圖片
靜態方法 URL.createObjectURL() 可用來將 File 物件或是 Blob 物件,變成一個帶有 URL 的 DOMString 以代表參數中所傳入的物件。
Blob (Binary Large Object)
Blob 物件為不可變物件。Blob 中的資料並不一定是 JavaScript 原生的格式。使用 File 介面基於 Blob,繼承 blob 並擴充其功能以支援操作使用者系統上的檔案。
objectURL = URL.createObjectURL(blob);
JavaScript
$("input[type=file]").on("change", function () { function getObjectURL(file) { if (window.URL != undefined) { url = window.URL.createObjectURL(file); return url; } } var objURL = getObjectURL(this.files[0]); document.getElementById("image").src = objURL; document.getElementById("imgBlob").textContent = objURL; });
Html
<p><input type="file" accept="image/*" /></p> <p><b id="imgBlob">-</b></p> <p><img id="image" src="images/Architecture-Build.png" alt="" /></p>
每次呼叫 createObjectURL() 都會產生一個新的 URL 不論是否曾經是同一物件產生過。當不再需要的時候將釋放它們。瀏覽器也會在 document 被 unload 時自動釋放它們,然而當有安全的時機考量時則採用手動的釋放。
可嘗試更改以下圖片、產生一個 blob
URL