Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
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
Tags more
Archives
Today
Total
관리 메뉴

두리공장

[Spring & jQuery] 파일 및 Json 데이터 업로드 (file & json data) 본문

java

[Spring & jQuery] 파일 및 Json 데이터 업로드 (file & json data)

두리공장 2022. 5. 30. 00:52

파일 업로드를 하려고 한다. 그런데, 파일만 올려야되는 것은 아니고, json data도 동시에 업로드 해야 한다면?

먼저, html 부터 작성해 본다.

<form action="upload" id="uploadForm" method="post" enctype="multipart/form-data">
    <input type="file" name="file1" id="file1" style="display:none" accept=".gif, .jpg, .jpeg, .png" />
    <button type="button" class="fileUploadBtn" id="add_file1"><span class="blind">사진추가</span></button>
</form>

.
.
.
<script type="text/javascript">
	$(document).ready(function(){
    /* 파일첨부버튼 클릭시 */
    $("#add_file1").bind("click", function (){
        $("#file1").click();

    });
    /*파일이 변경된 경우*/
    $("#file1").on("change", function(e){
        handleImgFileSelect(e, function(result){
            if(result){
                fn_submit();
            }
            else{
                alert("확장자는 이미지 확장자만 가능합니다");
                return;
            }
        });
    });
    
    //이미지 여부 확인
    function handleImgFileSelect(e, callback) {
        console.log("e:",e);
        var files = e.target.files;
        var filesArr = Array.prototype.slice.call(files);
        var reg = /(.*?)\/(jpg|jpeg|png|bmp)$/;
        var result = true;
        for(var i =0; i < filesArr.length; i++){
            if(!filesArr[i].type.match(reg)){
                result = false;
            }else{
                if(result) {
                    result = true;
                }else{
                    result = false;
                }
            }
        }
        callback(result);
    }
    
    //파일 업로드
    function fn_submit(){
        var jsondata = {"custno": "110111", "gubunname": "자동차등록증"};
        var form = $("#form")[0];
        var formData = new FormData();
        formData.append("file", $("#file1")[0].files[0]);
        formData.append("jsondata", new Blob([JSON.stringify(jsondata)], {type: "application/json"}));

        $.ajax({
            url: "http://localhost:8080/file/upload",
            type: "POST",
            processData: false,
            contentType: false,
            data: formData,
            success: function(res){
                alert("파일 업로드를 성공하였습니다");
                console.log("res:", res);
            },
            error: function(err){
                alert(err.responseText);
            }
        });
    }
</script>

"사진추가" 버튼(add_file1)에 클릭 이벤트를 건다. 버튼을 클릭하면 파일 업로드 다이얼로그 창이 뜬다.(accept 에 확장자를 등록하면 다이얼로그 창에 필터 기능이 적용된다)
파일업로드시 이미지 확장자만 첨부가 가능하도록 handleImgFileSelect 함수를 이벤트 발생시 호출해 준다. 파일명이 이미지인 경우에만 서버에 업로드 할 수 있다.

formData에 두가지 데이터 타입을 동시에 업로드 해야 하므로, formData.append에 file과 jsondata를 추가하되, jsondata에는 contentType 을 application/json으로 명시해 두어야 한다.

이제, 서버측 코드를 작성해 보자.

@RequestMapping(value = "/file")
@RestController
public class FileController {

    private String path = System.getProperty("user.dir");

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public FileVO upload(@RequestPart(value = "file", required = false)MultipartFile multi,
                         @RequestPart(value = "jsondata") FileVO fileVO) {
        try{

            String uploadPath = path + "/upload";
            String originalFilename = multi.getOriginalFilename();
            String ext = originalFilename.substring(originalFilename.lastIndexOf("."),originalFilename.length());
            long size = multi.getSize();
            String saveFilename = originalFilename;

            if(!multi.isEmpty()){
                File file = new File(uploadPath, multi.getOriginalFilename());
                multi.transferTo(file);

                fileVO.setResultcode("0");
                fileVO.setErrorMsg("");

            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            fileVO.setErrorMsg(e.getMessage());
            fileVO.setResultcode("1");
        }
        return fileVO;
    }

}

프로젝트의 디렉토리 위치를 찾기 위해서 System.getProperty("user.dir");을 사용하였다.
file 과 Jsondata 를 동시에 받기 위해서 @RequestPart 를 사용하였다. JsonData는 VO에 미리 선언해 준다.

@Data
public class FileVO {
    private String custno;
    private String gubunname;
    private String gubuncode;
    private String resultcode;
    private String errorMsg;
}

이렇게 하고나서 서버에서 파일을 업로드 하면, 정상적으로 응답이 온다..

{"custno":"110111","gubunname":"자동차등록증","gubuncode":null,"resultcode":"0","errorMsg":""}

끝.