图片上传预览
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <input type="file" id="photo"> <div id="click" style="width: 200px; height: 200px; border: 1px solid #000;"></div> <script> document.getElementById('photo').addEventListener('change',function(e){ var files = this.files; var img = new Image(); var reader = new FileReader(); reader.readAsDataURL(files[0]); reader.onload = function(e){ var mb = (e.total/1024)/1024; if(mb>= 2){ alert('文件大小大于2M'); return; } console.log(this.result);//base64 img.src = this.result;//有图片节点可以直接传输到对应节点src img.style.width = "100%"; img.style.height= "100%"; document.getElementById('click').style.width="200px"; document.getElementById('click').style.height="200px"; document.getElementById('click').innerHTML = ''; document.getElementById('click').appendChild(img); } }); </script> </body> </html>