js:
window.onload = function () { var input = document.getElementById('input-file'), info = document.getElementById('info'), preview = document.getElementById('preview'); input.addEventListener('change',function () { preview.style.backgroundImage = ''; if(!input.value){ info.innerText = '没有选择文件'; return false; } var file = input.files[0]; info.innerText = '文件名:' + file.name + '<br>' + '文件大小:' + file.size + '<br>' + '最后修改时间:' + file.lastModifiedDate; if(file.type != 'image/png' && file.type != 'image/jpeg' && file.type != 'image/gif'){ var p = document.createElement('p'); p.innerText = '不是有效的图片文件格式,请重试!'; info.appendChild(p); return false; } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { var data = e.target.result; preview.style.backgroundImage = 'url('+data+')'; } }) }
html:
<div class="testInput"> <p><input type="file" id="input-file" /></p> <p id="info"></p> <p id="preview" style="width: 400px; height: 500px;"></p> </div>