- 파일 업로드에 대한 비동기 처리를 위한 ajax 업로드 샘플

- 업로드 진행비율 ( 프로그래스바 등 ) 관련 처리 기본 코드 포함

 


<div style="display:block; background-color: #ffffff; width:600px; padding: 10px 10px 10px 10px;">
    <form id="fileWriteForm" name="fileWriteForm" method="post" enctype="multipart/form-data">

    <table class="yym_tbl" style="table-layout: fixed;">
        <tr>
            <td style="text-align: right; border-right: none;"><input type="file" id="fileToUpload" name="fileToUpload"></td>
            <td style="text-align: right; border-left: none;"><button type="button" id="btn_upload" class="btn btn-primary" onclick="func_ajaxFileUpload();">upload</button></td>
        </tr>
    </table>
    </form>
</div>

<script src="./jquery.form.js"></script>
<script>
    function func_ajaxFileUpload()
    {
        console.log( "exec:func_ajaxFileUpload" );

        if( jQuery("#fileToUpload").val().trim().length == 0 )
        {
            alert("전송대상파일이 선택되지 않았습니다.");
            return false;
        }//	end if
        
        let targetUrl       	=	"[ upload 파일에 대한 처리 경로 URL ]";

        jQuery("#fileWriteForm").ajaxSubmit(
            {
                url			: targetUrl,
                type		: "post",
                success		: function(data)
                {
                    console.log( data );
                    
                    // @ 서버에서 처리된 결과를 JSON 으로 리턴받아서 처리하는 샘플 시작

                    let rtnJson	    =   null;
                    try {
                        rtnJson	=	jQuery.parseJSON(JSON.stringify(data));
                    } catch (error) {

                        alert( error );
                        alert( "Return String Type ERROR - JSON parsing error" );
                    }//	end try
                    console.log( rtnJson );
                    console.log( rtnJson.Result );
                    
                    if( rtnJson.Result == "SUCCESS" )
                    {
                        alert('처리성공');
                    }else{
                        alert('처리실패');
                    }// end if

                    jQuery("#fileToUpload").val('');
                    
                    // @ 서버에서 처리된 결과를 JSON 으로 리턴받아서 처리하는 샘플 끝

                },
                // @ 업로드 진행률 출력 관련 부분
                xhr: function()
                {                	
                    let xhr = jQuery.ajaxSettings.xhr();
                    xhr.upload.onprogress = function(e)
                    {
                        let per =   Math.round( ( e.loaded * 100 / e.total )  * 100) / 100;
                        console.log(per);
                    };
                    return xhr;
                },
            }
        );

    }//	end function
</script>