1. 程式人生 > >type=file上傳的圖片進行預覽

type=file上傳的圖片進行預覽

html:

<input type="file" 
       onchange="changepic(this)" 
       id="file" 
       accept="image/png, image/jpeg, image/jpg" />
<div class="up-img">
       <img id="upload-img" src="" alt="" />
</div>

方法一: 通過src載入圖片的base64預覽圖片

function changepic(that){     
    var reads = new FileReader();
    var f = document.getElementById('file').files[0];          
    reads.readAsDataURL(f);         
    reads.onload = function (e){         
        document.getElementById('upload-img').src = reads.result;
    };
}

方法二: 獲取圖片的本地url

function changepic(obj) {
     var newsrc=getObjectURL(obj.files[0]);
     document.getElementById('upload-img').src = newsrc;
}

function getObjectURL(file) {
     var url = null ;        
     if (window.createObjectURL!=undefined) { // basic
             url = window.createObjectURL(file) ;
         } else if (window.URL!=undefined) { // mozilla(firefox)
             url = window.URL.createObjectURL(file) ;
         } else if (window.webkitURL!=undefined) { // webkit or chrome
             url = window.webkitURL.createObjectURL(file) ;
         }
         return url ;
     }