2017年3月7日 星期二

JavaScript將上傳圖片用二進位URL讀取

範例網址:用FileReader讀取檔案

若要監看當前的 blob 存儲狀態,Chrome內還有一個頁面可以監看:chrome://blob-internals/

html:
<input type="file" id="myFile" accept="image/*" />

javascript:
var x = document.getElementById("myFile"),
    htmldiv = document.createElement('div'),
    htmlhref = document.createElement('a'),
    htmlimg = document.createElement('img');
x.onchange = function(){
    var url1 = URL.createObjectURL(x.files[0]);
    htmldiv.appendChild(htmlhref);
    htmlhref.innerHTML = 'href';
    htmlhref.setAttribute('target', '_blank');
    htmlhref.href = url1;
    htmlimg.src = url1;
    document.body.appendChild(htmldiv);
    document.body.appendChild(htmlimg);
    htmlimg.onload = function(){
        URL.revokeObjectURL(this.src);
    }
}