两种方法
1、
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>file上传图片</title> <style type="text/css"> .container{ min-height: 500px; border: 1px solid #f5f5f5; background-color: #ccc; } .img-holder{ 300px; height: 300px; border:1px solid #f00; } .img-holder img{ 100%; height: 100%; } </style> </head> <body> <h2>预览图片</h2> <div class="container"> <input class="img-selector" type="file" > <div id="upload_text"></div> <div id="progress_text"></div> <div id="img-holder"></div> </div> <script type="text/javascript"> let img_input = document.getElementsByClassName('img-selector')[0]; img_input.addEventListener('change',function(){ let imgHolder = document.getElementById('img-holder'); let uploadText = document.getElementById('upload_text'); let progressText = document.getElementById('progress_text'); let files = this.files; let reader = new FileReader(); let type = 'default'; if(/image/g.test(files[0].type)){ reader.readAsDataURL(files[0]); //将上传的资源生成链接 保存在result中 type = 'image' }else{ reader.readAsText(files[0]); //将上传的资源生text类型数据 type = 'text' } reader.onerror = function(){ uploadText.innerHTML = '您上传的图片出错,错误码是'+reader.error.code; } reader.onprogress = function(event){ if(event.lengthComputable){ progressText.innerHTML = event.loaded+'/'+event.total; } } reader.onload = function(){ let html = ''; switch(type){ case 'image': html = "<img src='"+reader.result+"' />"; break; case 'text': html = reader.result; break; } imgHolder.innerHTML = html } },false) </script> </body> <ml>
2、
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>file上传图片</title> <style type="text/css"> .container{ min-height: 500px; border: 1px solid #f5f5f5; background-color: #ccc; } #img-holder{ 300px; height: 300px; border:1px solid #f00; } #img-holder img{ 100%; height: 100%; } </style> </head> <body> <h2>预览图片</h2> <div class="container"> <input class="img-selector" type="file" > <div id="upload_text"></div> <div id="progress_text"></div> <div id="img-holder"></div> </div> <script type="text/javascript"> let img_input = document.getElementsByClassName('img-selector')[0]; img_input.addEventListener('change',function(){ let imgHolder = document.getElementById('img-holder'); let uploadText = document.getElementById('upload_text'); let progressText = document.getElementById('progress_text'); let files = this.files; let reader = new FileReader(); let url = createObjectURL(files[0]); if(url){ if(/image/g.test(files[0].type)){ imgHolder.innerHTML = "<img src='"+url+"'>" }else{ imgHolder.innerHTML = "不是图片" } } },false) function createObjectURL(blob){ if(window.URL){ return window.URL.createObjectURL(blob) }else if(window.webkitURl){ return window.webkitURl.createObjectURL(blon) }else{ return null } } </script> </body> <ml>