一个上传图片,预览图片的小demo

<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="UTF-8">  
    <title>3</title>  
<script>  
function getFullPath(obj) {  
    if (obj) {  
        //Internet Explorer   
        if (window.navigator.userAgent.indexOf("MSIE") >= 1) {  
            obj.select();  
            return document.selection.createRange().text;  
        }   
        //Firefox  
        if (window.navigator.userAgent.indexOf("Firefox") >= 1) {  
            if (obj.files) {  
                return obj.files.item(0).getAsDataURL();  
            }  
            return obj.value;  
        }   
  
        //兼容chrome、火狐等,HTML5获取路径         
        if (typeof FileReader != "undefined") {  
            var reader = new FileReader();  
            reader.onload = function(e) {  
                document.getElementById("pic").src = e.target.result + "";   
            }  
            reader.readAsDataURL(obj.files[0]);  
        } else if (browserVersion.indexOf("SAFARI") > -1) {  
            alert("暂时不支持Safari浏览器!");  
        }  
  
    }   
}  
  
function showPic(obj) {  
    var fullPath = getFullPath(obj);  
    if (fullPath) {  
        document.getElementById("pic").src = fullPath + "";  
    }  
}  
</script>  
</head>  
<body>  
    <input type="file" onchange="showPic(this)">  
    <img src="" id="pic">  
</body>  
</html> 

由于工作需要,自己写了个小demo,通过自己组装,可以实现一定的需求。

 原创文章如转载,请注明出处

原文地址:https://www.cnblogs.com/pongyc/p/7514561.html