關於html中圖片上傳預覽的實現


本地圖片預覽

第一種方法

<!DOCTYPE html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
<script type="text/javascript">
function change() {
    var pic = document.getElementById("preview"),
        file = document.getElementById("f");
    //得到后綴名
    var ext=file.value.substring(file.value.lastIndexOf(".")+1).toLowerCase();
     // gif在IE瀏覽器暫時無法顯示
     if(ext!='png'&&ext!='jpg'&&ext!='jpeg'){
         alert("圖片的格式必須為png或者jpg或者jpeg格式!"); 
         return;
     }
     var isIE = navigator.userAgent.match(/MSIE/)!= null,
         isIE6 = navigator.userAgent.match(/MSIE 6.0/)!= null;
 
     if(isIE) {
        file.select();
        var reallocalpath = document.selection.createRange().text;
 
        // IE6瀏覽器設置img的src為本地路徑可以直接顯示圖片
         if (isIE6) {
            pic.src = reallocalpath;
         }else {
            // 非IE6版本的IE由於安全問題直接設置img的src無法顯示本地圖片,但是可以通過濾鏡來實現
             pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")";
             // 設置img的src為base64編碼的透明圖片 取消顯示瀏覽器默認圖片
             pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
         }
     }else {
        html5Reader(file);
     }
}

function html5Reader(file){
     var file = file.files[0];
     var reader = new FileReader();
     reader.readAsDataURL(file);
     reader.onload = function(e){
         var pic = document.getElementById("preview");
         pic.src=this.result;
     }
 }


</script>
</head>
<body>
<form action="">
    <input type="file" multiple id="f" type="file" name="f" onchange="change()" >
    <img id="preview" alt="" src="" name="pic" class="file_img" style="margin-top: 5px;margin-left: 12px; width: 158px; height: 230px;"/>
</form>
</body>
</html>

 

第二種方法

<!DOCTYPE html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
<script type="text/javascript">
function previewFile() {
 var preview = document.querySelector('img');
 var file  = document.querySelector('input[type=file]').files[0];
 var reader = new FileReader();
 reader.onloadend = function () {
  preview.src = reader.result;
 }
 if (file) {
  reader.readAsDataURL(file);
 } else {
  preview.src = "";
 }
}
</script>
</head>
<body>
    <input type="file" onchange="previewFile()"><br>
    <img src="" height="200" width="300" alt="Image preview..."/>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM