jQuery ajax 를 사용하지 않는 jQuery 를 http://link2me.tistory.com/1142 에서 다루었다.


=== fileupload.js ===

$(document).ready(function() {
    $('#form').submit(function(){
        var
upfiles_cnt = $("input:file", this)[0].files.length;
        if(
upfiles_cnt == 0){
            alert('선택한 파일이 없습니다');
            return false; // form을 전송시키지 않고 반환
        }
    });
});

ajax 방식을 사용한 jQuery 를 구현해보자.

파일 업로드 현황을 progress bar 로 구현하려고 구글링을 하면서 개념 이해 및 테스트 중이다.

ajax 로 파일 전송시 현재 업로드한 파일 숫자가 0 인지 체크 로직을 추가하여 처리하도록 구현했다.

구글링을 해서 이 방법 저 방법 테스트를 해보니 formData 부분에서 에러가 발생하더라.


=== fileupload.js ===

$(document).ready(function() {

    $('#form').submit(function(e){
        //disable the default form submission
        e.preventDefault();

        //grab all form data <== 필요에 따라 코드 수정해서 사용해야 함.
        var form = $('form')[0];
        var formData = new FormData(form);


        var upfiles_cnt = $("input:file", this)[0].files.length;
        if(upfiles_cnt == 0){
            alert('선택한 파일이 없습니다');
            return false; // form을 전송시키지 않고 반환
        }


        $.ajax({
            url: "fileupload.php",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            dataType: "json",
            success: function (data) {
                $('.status').html(data + ' Files uploaded!').fadeIn();
            },
            error: function(){
                alert("error in ajax form submission");
            }
        });

        return false;
    });

});



Upload Progress bar 검색해보면 대부분 아래 코드와 유사한 것이 검색된다.

그런데 이코드를 수정해서 Upload 파일 갯수가 0이면 진행이 안되게 하려고 테스트 하니 잘 안된다.


=== fileupload.js ===
$(document).ready(function() {

    $('form').ajaxForm({
        /* set data type json */
        dataType:  'json',

        /* reset before submitting */
        beforeSend: function() {
            status.fadeOut();
            bar.width('0%');
            percent.html('0%');
        },

        /* progress bar call back*/
        uploadProgress: function(event, position, total, percentComplete) {
            var pVel = percentComplete + '%';
            bar.width(pVel);
            percent.html(pVel);
        },

        /* complete call back */
        complete: function(data) {
            status.html(data.responseJSON.count + ' Files uploaded!').fadeIn();
        }
    });
});



http://phppot.com/jquery/jquery-progress-bar-for-php-ajax-file-upload/ 사이트를 발견하고 이걸 참조하여 구현했더니 원하는 결과가 나온다.


아래 코드는 에러 없이 정상 동작한다.

//grab all form data
var form = $('form')[0];
var formData = new FormData(form);


그런데 파일 전송시

<input type="hidden" name="uid" value="">

<input type="file" id="file" name="file" multiple />

와 같이 이미지 파일 외에 uid 값까지 같이 전송되도록 하려니까 잘 전송이 안된다.


var formData = new FormData();
var files = $('#file')[0].files[0];
formData.append('file',files);
formData.append('uid',idx);

와 같이 해주고 나서 정상적으로 전송이 된다.


=== fileupload.js ===
$(document).ready(function() {

    $('#form').submit(function(e){
        //disable the actual submit of the form.
        e.preventDefault();
       
        //grab all form data
        var form = $('form')[0];
        var formData = new FormData(form);

        var upfiles_cnt = $("input:file", this)[0].files.length;
        if(upfiles_cnt == 0){
            alert('선택한 파일이 없습니다');
            return false; // form을 전송시키지 않고 반환
        }

        $(this).ajaxSubmit({
            // set data type json
            dataType:  'json',

            // reset before submitting
            beforeSend: function() {
                status.fadeOut();
                bar.width('0%');
                percent.html('0%');
            },

            // progress bar call back
            uploadProgress: function(event, position, total, percentComplete) {
                var pVel = percentComplete + '%';
                bar.width(pVel);
                percent.html(pVel);
            },

            complete: function(data) {
                status.html(data.responseJSON.count + ' Files uploaded!').fadeIn();
            },
            resetForm: true
        });
        return false;
    });
});



progress bar 가 나오는 ajax 방법으로 구현해보려고 시도하면서 검색/테스트 많이 했다.

나와 같은 jQuery 초보자를 위해서 고생하지 말라고 테스트한 파일을 첨부합니다.


fileupload_ajax.zip



도움되셨다면 공감 눌러주시거나 00 00 한번 해주시길

728x90
블로그 이미지

Link2Me

,

문자열 비교 strcmp

strcmp(string1,string2);


결과값

0 : 두 문자열이 같다.

<0 : string1 is less than string2

>0 : string1 is greater than string2


<?php
$mailing = $row['mailing'] = 1; // DB에서 읽어온 값이라 가정
if(!strcmp($mailing,"1")) {
  $mailing = "가입";
} else if(!strcmp($mailing,"2")) {
  $mailing = "완료";
} else if(!strcmp($mailing,"3")) {
  $mailing = "추가";
} else {
  $mailing = "거부";
}
echo $mailing;
?>


strcmp 를 잘못 사용하면 원하지 않는 결과가 나올 수 있음에 유의하자.

if(0 == NULL){
    echo "True";
} else {
    echo "False";
}

결과는 True 를 반환한다.


if(0 === NULL){
    echo "True";
} else {
    echo "False";
}

결과는 False 를 반환한다.

PHP에서 조건문을 느슨하게 비교하면 원하지 않는 결과가 나올 수 있다.


strcmp는 string(문자열)을 비교하라고 되어 있다.

그런데 문자열 대신 배열을 넣고 비교하면 어떤 결과가 나올까?


$a = Array("a");
$b = 'password';

if (!strcmp($a, $b)){
  echo "Strings are same !";
} else {
  echo "Strings are different";
}

결과

Warning: strcmp() expects parameter 1 to be string, array given in C:\AutoSet9\public_html\11.php on line 5
Strings are same !

보시는 바와 같이 $a 와 $b는 다음에도 불구하고 경고 메시지는 나오지만 결과는 동일하다고 출력한다.


$a = Array("a");
$b = 'password';

if (strcmp($a, $b) === 0){
  echo "Strings are same !";
} else {
  echo "Strings are different";
}

와 같이 해주면 경고메시지는 출력하지만 결과는 다르다고 출력한다.

Warning: strcmp() expects parameter 1 to be string, array given in C:\AutoSet9\public_html\11.php on line 5
Strings are different


하나더 살펴보자.

육안으로 확인하면 두개의 문자열은 서로 다르다. 하지만 결과는 느슨비교를 해서 True를 반환한다.

$something = 0;
echo ('password' == $something) ? 'True' : 'False';


따라서 === 비교를 해주어야 한다.

$something = 0;
echo ('password' === $something) ? 'True' : 'False';


$something = 0;
echo ('1' == $something) ? 'True' : 'False';
이 경우에는 같은 정수를 비교하므로 == 를 사용해도 False 를 반환한다.

문자열과 숫자를 비교시 느슨비교를 하면 엉뚱한 결과가 나옴을 확인할 수 있다.


<?php
$val = 20;
if($val === '20'){
    echo '결과는 동일하다';
} else {
    echo '$val은 정수형, "20"은 문자열형이다.';
    echo '<br />결과는 다르다.';
}
?>


Don't use == in PHP. It will not do what you expect.

Even if you are comparing strings to strings, PHP will implicitly cast them to floats and do a numerical comparison if they appear numerical.

느슨한 비교를 하면 원하지 않은 결과가 나올 수 있음에 유의하자!


728x90
블로그 이미지

Link2Me

,