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
관리 메뉴

어리바리 신입 개발자의 얼렁뚱땅 개발 기록 ✨

[ Java / SpringBoot / database ] RESTful한 게시판 만들기6 / 첨부파일 크기 오류 본문

REST API

[ Java / SpringBoot / database ] RESTful한 게시판 만들기6 / 첨부파일 크기 오류

낫쏘링 2023. 9. 11. 15:16
728x90
파일 크기 제한이 있다보니 파일 크기를 넘어가면 MaxUploadSizeExceededException 오류가 발생한다.

프로퍼티 파일에 다음 코드를 추가해서 체크 시점을 지연시킨 후 
# 원래 파일 업로드시 HTTP 요청 데이터가 스프링 MVC의 컨트롤러 메서드로 전달되기 전
# 즉, 요청 파싱 단계에서 파일 크기를 체크해서 에러를 발생시킨다고 한다.
# 그래서 해당 파일에 접근하는 시점에 파일을 체크하게 한다. (체크 시점을 지연시키는 것)
spring.servlet.multipart.resolve-lazily=true​


컨트롤러에 예외 처리를 해줘도 되지만,

@ExceptionHandler(MaxUploadSizeExceededException.class)
public String handleMaxUploadSizeExceededException(MaxUploadSizeExceededException maxUploadSizeExceededException,
													RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute("errorMessage", "파일 용량이 초과되었습니다.");

    return "redirect:/board/write";
}


굳이 이미 에러 상태인데 파일을 서버에 전송할 필요가 없을 것 같기도하고 작성 화면 그 상태로 새로고침 하고싶지 않아서, 자바스크립트를 통해 클라이언트 측에서 미리 체크하기로 했다.

const insertBtn = document.querySelector('#insertBtn');
const insertForm = document.querySelector('#frm');

insertBtn.addEventListener('click', e => {
    const maxOneFileSize = 1 * 1024 * 1024;
    const maxAllFileSize = 5 * 1024 * 1024;
    let sumFileSize = 0;
    let isOneTrue = true;
    let isAllTrue = true;

    const files = document.querySelector('#files');
    // input의 type이 file인 태그의 경우 .files라는 내장 프로퍼티를 사용 가능하다.
    // .files라는 프로퍼티는 type이 file인 input을 요소로 선택해서 사용할 수 있고,
    // 사용자가 선택한 파일들의 정보를 담고 있다.
    const filesInfo = files.files;

    for(const oneFile of files){
        sumFileSize += oneFile.size;
        if(oneFile.size >maxOneFileSize){
            alert("파일 용량이 초과되었습니다.");
            isOneTrue = false;
            break;
        }				
    }

    if(sumFileSize > maxAllFileSize) { isAllTrue = false; }			
    if(isOneTrue && isAllTrue) { insertForm.submit(); }
});

그럼 새로고침 없이 글 작성하던 상태 그대로 경고창만 뜬다!

728x90