【小编推荐】通过JS实现上传图片前的本地预览功能

2016-06-13   |   发布者:梁国芳   |   查看:3320次

前端开发
 上传图片前本地预览
相关代码:
注意:本文件需要引入bs框架中的模态框
<!doctype html>
<html lang="en">
<head> 
<meta charset="UTF-8">
<title>JS本地图片预览</title> 
<link rel="stylesheet" href="./BS/css/bootstrap.min.css" />
<script src="./BS/js/jquery.min.js"></script>
<script src="./Bs/js/bootstrap.min.js"></script>
<style>
.modal-content{
width:250px;
height:265px;
}
.modal-dialog{
width:250px;
height:265px;
}
.modal-header{
border-bottom:none;
}
#portrait{
margin-top:5px;
margin-left:10px;
}
</style>
</head> 
<body> 
<input type="file" name="file""showPreview(this)" id="file" />
<p"show()" id="show" data-toggle="modal" data-target="#myModal">预览</p>
<p"del()" id="del">删除</p>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
   <div class="modal-content">
     <div class="modal-header">
       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
       <img id="portrait" src="">  
     </div>
   </div><!-- /.modal-content -->
 </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body> 
<script>
function showPreview(source) {  
            var file = source.files[0]; //定义一个文件对象
            if(window.FileReader) {  
                var fr = new FileReader();  
                fr.onloadend = function(e) {
               if(!/image\/\w+/.test(file.type)){  
                   return false;  
               }   
                    // document.getElementById("portrait").src = e.target.result;  //e.target.result代表图片本地路径
                    src=e.target.result;
                };  
                fr.readAsDataURL(file);  
            }  
        }
function show(){
obj=document.getElementById("portrait");
obj.src=src;
obj.style.width="200px";
}
function del(){
obj=document.getElementById("portrait");
obj.src="";
obj.style.width="";
obj2=document.getElementById("file");
obj2.value="";
}
</script>
</html>