2016-01-13

上傳圖像預覽

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

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

1
2
<input type="file" id="fileSel" multiple="" accept="image/*">
<div id="info"></div>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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 += "<span>檔名:" + file.name + ", 大小:" + file.size + "B" + ", w:" + this.width + ", h:" + this.height + "</span>";
info.appendChild(this);
//window.URL.revokeObjectURL(this.src);
}
}

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