JAVASCRIPT/JQUERY/AJAX

[javascript-jQuery] 파일 확장자 체크하기

최고관리자
2017.12.08 10:56 7,537 0

본문

var thumbext = document.getElementById('file').value; //파일을 추가한 input 박스의 값


thumbext = thumbext.slice(thumbext.indexOf(".") + 1).toLowerCase(); //파일 확장자를 잘라내고, 비교를 위해 소문자로 만듭니다.


if(thumbext != "jpg" && thumbext != "png" &&  thumbext != "gif" &&  thumbext != "bmp"){ //확장자를 확인합니다.


alert('썸네일은 이미지 파일(jpg, png, gif, bmp)만 등록 가능합니다.');


return;


}


출처: http://blog.taeseong.me/279 [사과 냄새나는 IT이야기 TAESTORY,]




// 정규식으로 파일 확장자 체크

<script language="javascript"> 

//체크방법 1 

function upload() { 

if (document.form.userfile.value.match(/(.jpg|.gif)$/) ) 

alert("맞음"); 

else 

alert("아님"); 


//체크방법 2 

function chk(obj) { 

if (/(\.gif|\.jpg|\.jpeg)$/i.test(obj.value) == false) { 

alert("이미지 형식의 파일을 선택하십시오"); 

</script>





[jQuery] 파일업로드시 필요한 확장자체크, 용량체크 및 이미지 가로 세로 값 구하기


$("input[id=nt_img_real").change(function(){

 

    // 필드 채워지면

    if($(this).val() != ""){

        // 확장자 체크

            var ext = $(this).val().split(".").pop().toLowerCase();

            if($.inArray(ext, ["gif","jpg","jpeg",,"png"]) == -1){

                alert("gif, jpg, jpeg, png 파일만 업로드 해주세요.");

                $(this).val("");

                return;

            }

            

            // 용량 체크

            var fileSize = this.files[0].size;

            var maxSize = 1024 * 1024;

            if(fileSize > maxSize){

                alert("파일용량 1MB을 초과했습니다.");

                $(this).val("");

            }

            

            // 가로,세로 길이

            var file = this.files[0];

            var _URL = window.URL || window.webkitURL;

            var img = new Image();

             

            img.src = _URL.createObjectURL(file);

            img.onload = function() {

            //    alert(img.width + " " + img.height);

                $("#img_width").val(img.width);

                $("#img_height").val(img.height);

            }

    }

});

댓글목록 0

등록된 댓글이 없습니다.