20241111(월) Spring 파일 업로드

Dodo Lee·2024년 11월 11일

[ 이미지가 사용자에게 보이는 과정 ]

1. 클라이언트가 서버에 이미지 요청

<img src="경로">

위 태그가 작성되어 있으면 브라우저(클라이언트)는 src에있는 경로를 서버에 요청
→ 클라이언트가 서버에 이미지 파일을 보내달라고 요청하는 HTTP 요청으로 처리

< 예시 >
<form action="page/file/test" method="POST" enctype="multipart/form-data">
	<input type="file" name="uploadFile>
    <button>제출하기</button>
</form>

위와 같이 요청을 보낼 시,
서버는 /page/file/test 요청 주소와 매핑되어있는 서버 경로를 찾음
(config 파일에서 서버의 경로를 매핑)

2. 서버 Controller

MultipartConfigElement
파일 업로드를 처리하는데 사요되는 MultipartConfigElement를 구성하고 반환
파일 업로드를 위한 구성 옵션을 설정하는데 사용
업로드 파일의 최대크기, 메모리에서의 임시 저장경로 등 설정 가능

MultipartResolver
MultipartFile을 처리해주는 해결사
클라이언트로부터 받은 multipart 요청을 처리하고,
이 중에서 업로드된 파일을 추출하여 MultipartFile 객체로 제공하는 역할

<예시>
@PostMapping("file/test")
public String fileUpload(@RequestPara("uploadFile") MultipartFile uploadFile,
						 RedirectAttributes ra) throws Exception{
                        
    String path = service.fileUpload(uploadFile);
   
    if(path != null ){
        ra.addFlashAttribute("path", path);
    }
   
    return "redirect:/myPage/fileTest";
}

3. 서버 Service

MultipartFile 제공 메서드

  • getSize()
    : 파일 크기
  • isEmpty()
    : 업로드한 파일이 없을 경우 true / 있으면 false
  • getOriginalFileName()
    : 원본 파일명
  • transferTo(경로)
    : 메모리 또는 임시 저장 경로에 업로드된 파일을 원하는 경로에 실제로 전송(서버 어떤 폴더에 저장할지 지정)
<예시>
public String fileUpload(MultipartFile uploadFile) throws Exception{
	if( uploadFile.isEmpty() ){
    	return null;
    }
   
    uploadFile.transferTo(new File("C:/uploadFiles/test/"
                                    +uploadFile.getOriginalFilename()));
   
    return "/myPage/file/" + uploadFile.getOriginalFilename();
}
profile
연습생

0개의 댓글