2016-01-13

上傳圖像預覽

其實要讀取圖像的資訊跟預覽,無須動用到FileReader。

https://jsfiddle.net/ef0vg2sb/2/



window.URL = window.URL || window.webkitURL;

var fileSel = document.getElementById("fileSel");
var info = document.getElementById("info");

fileSel.addEventListener("change", function(e) {
  e.preventDefault();
  if (this.files && !!this.files.length) {
    info.innerHTML = "";
    for (var i = 0; i < this.files.length; i++) {
      preview(this.files[i]);
    }
  }
}, false);

var preview = function(file) {
  var img = document.createElement("img");
  img.src = window.URL.createObjectURL(file);

  img.onload = function() {
    info.innerHTML += "檔名:" + file.name + ", 大小:" + file.size + "B" + ", w:" + this.width + ", h:" + this.height + "";
    info.appendChild(this);
    //window.URL.revokeObjectURL(this.src);
  }

}

ref:
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications