file upload하기 : $.ajax, XMLHttpRequest() 사용

 

$.ajax 및 XMLHttpRequest 를 사용하여 파일업로드를 할 수 있습니다. 

$.ajax 는 jQuery 라이브러리로 내부적으로 javascript 의 XMLHttpRequest 객체를 사용합니다.

XMLHttpRequest를 사용하기 편하게 구현해 놓은게 $.ajax 라고 보시면 될 듯 합니다.

 

파일 업로드 form 이 존재하며 파일 업로드 function을 호출 하는 jsp와

파일 업로드 function 이 분리되어 있는 fileupload.js 로 크게 두 파일로 소스를 분리했습니다.

 

jQuery version 은 3.1.1 이며,  jQuery 버전이 다른 경우 제대로 동작하지 않을 수 있습니다. 

 

 

[fileupload.js]

jQuery lib 사용시 $.ajax 사용하여 파일업로드를 구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 
var httpFileUpload = {
    uploadStart : function(fileElement, callback){
        const file = fileElement[0];
        if(!file){
            throw new Error("file not exists");
        } else {
            const uploadFile = file.files[0];
            if(!uploadFile || !uploadFile.size || !uploadFile.name || uploadFile.size === 0){
                throw new Error("upload file is required");
            } else {
                    const url = "http://uploadurl";
                    const form = new FormData();
                    form.append('file', file.files[0]);
                    var returnObj = new Object();
                    
                    $.ajax({
                        type    : 'post',
                        url        : url,
                        data     : form,
                        cache : false,
                        enctype : 'multipart/form-data',
                        contentType : false,
                        processData : false,
                        timeout : 600000
                    })
                    .done(function (data, textStatus, xhr) {
                        var tmp = null;
                        switch(xhr.status){
                            case 201:
                                console.log("uploaded!");
                                returnObj.result_cd = "1";
                                break;
                            case 404:
                                console.log("404");
                                returnObj.result_cd = "404";
                                break;
                            default:
                                console.log("not 201 404");
                                returnObj.result_cd = "0";
                                break;
                        }
                        callback(returnObj);
                    })
                    .fail(function(data, textStatus, errorThrown){
                        console.log("http upload fail : "+errorThrown);
                        returnObj.result_cd = "0";
                        callback(returnObj);
                    });
            }
        }
    }    
}
cs

$.ajax 의 .done .fail 의 callback param은 여기를 참고

 

 

[fileupload.js]

javascript 로 파일업로드를 구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var httpFileUpload = {
    
    uploadStart : function(fileElement, callback){
        const file = fileElement[0];
 
        if(!file){
            alert("file not exists");
            throw new Error("file not exists");
        }
 
        const url = "http://uploadurl";
 
        const form = new FormData();
        form.append('file', file.files[0]);
 
        const returnObj = new Object();
        
        const request = new XMLHttpRequest();
        
        request.onload = function(e){
            if(request.status == 201){
                console.log("uploaded!");
                returnObj.result_cd = "1";
            } else if(request.status == 404){
                console.log("404");
                returnObj.result_cd = "404";
                callback(returnObj);
            } else {
                console.log("not 201 404");
                callback(returnObj);
                returnObj.result_cd = "0";
            }
            callback(returnObj);
        };
        request.open('POST', url);
        request.send(form);
    }
}
 
cs

 

[위 모듈(fileupload.js)을 사용하는 jsp]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>                       
<script type="text/javascript" src="${rquest.getContextPath()}/resources/js/jquery-3.1.1.min.js"></script>
<script>
function uploadStartFront(){
    httpFileUpload.uploadStart($("#file"), function(returnData){
        if(returnData.result_cd == "1"){
            alert("업로드 성공");
        } else {
            if(typeof returnData.result_msg !== "undefined"){
                alert("업로드 실패 " + "[" + returnData.result_cd + "]");
            } else {
                alert("업로드 실패 " + "[" + returnData.result_cd + ":" + returnData.result_msg +"]");
            }
        }
        console.log(returnData);
    });
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
 
<body>
    <div class="inner_wrap" style="padding-left : 350px;">
    <form id ="frm" class="form-horizontal" method="post" action="" enctype="multipart/form-data">
        <input type="file" class="form-control1" id="file" name="file" style="border:0px solid black;"/>
        <button type="button" class="btn_s" onclick="javascript:uploadStartFront();">업로드시작</button>
        <button type="button" class="btn_s">취소</button>
    </form>
    </div>
</body>
 
<script type="text/javascript" src="${rquest.getContextPath()}/resources/js/fileupload.js"></script>
 
</html>
cs

 

파일을 내부 was 로 송신할 때나, 외부 서버로 송신할 때나 목적지 주소(위 코드에서 url)를 제외하곤 코드가 다를게 없지만, 외부 서버로 파일을 송신하는 경우 CORS 및 mixed contents 문제를 유의해야 합니다.

 

CORS 및 mixed contents 에 대한 내용은 추후 공부 및 정리하여 포스팅 하겠습니다.

반응형

+ Recent posts