728x90

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 한번 해주시길

블로그 이미지

Link2Me

,