html:html
<div class="uploadpit"> <div class="uploadpit-btn"><span>上傳圖片</span> <input type="file" value="上傳圖片" onchange="imgPreview(this,'preview_img')" accept="image/*" id="file5" multiple='multiple'> </div> <div class="preview priv_textword_img" id="preview_img"> </div> </div>
關於樣式,給input ,opacity:0; (ie兼容性問題,之前文章寫有)。app
js:this
function imgPreview(obj,id) { var fl = obj.files.length; for (var i = 0; i < fl; i++) { var file = obj.files[i]; console.log(file) var reader = new FileReader(); //讀取文件過程方法 reader.onloadstart = function(e) { console.log("開始讀取...."); } reader.onprogress = function(e) { console.log("正在讀取中...."); } reader.onabort = function(e) { console.log("中斷讀取...."); } reader.onerror = function(e) { console.log("讀取異常...."); } reader.onload = function(e) { console.log("成功讀取...."); if ((file.size / 1024).toFixed(0) > 4096) { alert("上傳圖片不得超過4M!") return false; } else { var imgstr = '<img style="width:100%;" src="' + e.target.result + '"/>'; var oimgbox = document.getElementById(id); var ndiv = document.createElement("li"); ndiv.innerHTML = imgstr; ndiv.className = "img-div"; oimgbox.appendChild(ndiv); } } reader.readAsDataURL(file); } }