1. 程式人生 > >JQUERY上傳圖片本地預覽寫法

JQUERY上傳圖片本地預覽寫法

HTML:

<div class="pic">
                <label for="pic1">
                    <input id="pic1" type="file" />
                    <img class="pic1 picc" src="images/pic_03.jpg" alt="" />
                </label>
                <label for="pic2">
                    <input id="pic2" type="file" />
                    <img class="pic2 picc" src="images/pic_03.jpg" alt="" />
                </label>
                <label for="pic3">
                    <input id="pic3" type="file" />
                    <img class="pic3 picc" src="images/pic_03.jpg" alt="" />
                </label>

</div>


JS:

<script type="text/javascript">
        $(function() {
            $('.picc').each(function(i){
                $(this).click(function(){
                    $(this).prev('input').on("change",function(){


                        //判斷後綴
                        var filepath=$(this).val();
                        var extStart = filepath.lastIndexOf(".");
                        var ext = filepath.substring(extStart, filepath.length).toUpperCase();
                        //console.log(extStart);
                        if(ext != ".JPG" && ext != ".PNG" && ext != ".JPEG"){
                            alert("上傳的格式不對!");
                            return false;
                        }


                        //判斷大小
                        var fileSzie = $(this)[0].files[0].size; 
                        //console.log(fileSzie);
                        if(fileSzie > 10 * 1024 * 1024){
                            alert("圖片太大咯!");
                            return false;
                        }


                        //圖片預覽
                        var objUrl = getObjectURL(this.files[0]); //獲取圖片的路徑,該路徑不是圖片在本地的路徑
                        //console.log(objUrl);
                        if(objUrl) {
                            $(this).next('.picc').attr("src", objUrl) ; //將圖片路徑存入src中,顯示出圖片
                        }


                    });
                })
            })
        });


        
        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 ;
        }
    </script>