jq實現上傳頭像並實時預覽功能

李文楊發表於2017-08-24

效果

 

 

頁面結構

 <form action="" name="form0" id="form0">  
        <input type="file" name="pic" id="pic" class="file0"/>  
        <a href="">選擇影象</a>  
        <span id="info"></span>  
        <img src="" alt="" id="img0" width="100" />  
    </form>  

JS程式碼

 $(function(){  
            $("#pic").change(function(){  
                if($.browser.msie){  
                    $("#img0").attr("src",$(this).val())  
                    $("#info").text("當前選擇的檔案:"+$(this).val())  
                }else{  
                    $("#info").text("當前選擇的檔案:"+$(this).val())  
                    var objUrl=getObjectURL(this.files[0]);  
                    console.log("objUrl="+objUrl);  
                    if(objUrl){  
                        $("#img0").attr("src",objUrl);  
                    }  
                }  
            })  
            //建立一個可存取到該file的url  
            function getObjectURL(file) {  
                var url = null ;   
                if (window.createObjectURL!=undefined) {  
                    url = window.createObjectURL(file) ;  
                } else if (window.URL!=undefined) {   
                    url = window.URL.createObjectURL(file) ;  
                } else if (window.webkitURL!=undefined) {   
                    url = window.webkitURL.createObjectURL(file) ;  
                }  
                return url ;  
            }  
        })  

需要注意的是如果使用jQuery 1.9及以上版本移除了$.browser可以使用$.support來替代

相關文章