Home >Web Front-end >JS Tutorial >JavaScript implements real-time image preview function
The content of this article is to share with you the real-time image preview function using JavaScript, which has a certain reference value. Friends in need can refer to
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .img{ width: 170px; height: 170px; border: 1px solid lightgray; } .img>img{ width: 170px; height: 170px; } </style> </head> <body> <input type="file" id="file"> <p class="img"> <img src="" alt="" id="img"> </p> <script> window.onload=function () { /*请将input的id设为file img标签的id设为img**/ var file=document.getElementById('file'); var img=document.getElementById('img'); var dataImg; file.onchange=function () { //判断是否支持FileReader if(typeof FileReader==="undefined"){ alert('您的浏览器不支持'); } //读取文件 var result=this.files[0]; //获取文件类型 var type=result.type; if(!type){ alert('请上传图片'); }else { //判断图片类型 type=type.split('/')[1]; console.log(type); //使用正则匹配判断是否是jpeg,jpg,png,bmp,gif图片类型 if(type.match(/^(jpg|bmp|png|jpeg|gif)$/g)){ console.log(result); //声明一个fileReader var reader=new FileReader(); //以数据流的形式读取图片 reader.readAsDataURL(result); //图片读取完毕后执行操作 reader.onload=function (e) { //获取图片读取结果 dataImg=this.result; //加载图爿到标签上 img.setAttribute('src',dataImg); }; } else { alert("请上传图片格式"); //清空input this.value=''; } } } } </script> </body> </html>
Related recommendations:
Two front-end implementations of real-time preview of image uploads A way
Upload pictures real-time preview
js: realize uploading pictures Instant preview
The above is the detailed content of JavaScript implements real-time image preview function. For more information, please follow other related articles on the PHP Chinese website!