본문 바로가기
개념서

[Spring 실력편] MultipartFile

by 사서T 2023. 2. 1.

MultipartFile이란?

MultipartFile이란 multipart 요청을 통해 받은 파일이다. 파일 내용은 임시 저장소(메모리나 디스크)에 저장되며 요청 처리가 끝날 때 임시 저장소에서 삭제된다.

 

- String getName() : multipart form 파라미터의 이름을 반환

- String getOriginalFilename() : 실제 등록된 파일의 이름을 반환

- String getContentType() : 파일의 컨텐츠 타입을 반환(확장자 포함)

- boolean isEmpty() : 업로드된 파일의 존재 여부를 반환

- long getSize() : 업로드된 파일의 크기를 반환(파일이 없는 경우 0 반환)

- byte[] getBytes() : 업로드된 파일의 내용을 바이트 배열로 반환

- InputStream getInpuStream() : 업로드된 파일의 내용을 읽기위한 InputStream을 반환

- Resource getResource() : 업로드된 파일을 표현하는 Resource를 반환

- void transferTo(File dest) : 업로드된 파일을 대상 파일로 전송

- void transferTo(Path dest) : 업로드된 파일을 대상 파일로 전송

 

MultipartFile 어떻게 사용할까?

위에서 확인한 메서드의 일부를 이용해 출력되는 형태를 확인해보자. 우선 파일 전송을 위한 html을 정의하자. form 형태로 전송하며 enctype="multipart/form-data"를 선언해주자. <input> 의 타입은 file로 선언하고 현재는 하나의 파일만 넘길 예정이기 때문에 multiple="multiple" 옵션은 생략한다.

 

<form.html>

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <form th:action="@{/multipart/upload1}" method="post" enctype="multipart/form-data">
        <label> detailImg : <input type="file" name="file" accept="image/*"></label><br/>
        <button type="submit">등록</button>
    </form>
</div>
</body>
</html>

 

html 작성이 끝났다. 이제 html 파일을 호출하기위한 메서드와 form data를 처리하기 위한 메서드를 컨트롤러에 작성해주자. 메서드의 매개변수 매핑에 대한 설명은 MultipartResolver를 통해 알아보고 여기선 매핑이 정상적으로 된 이후에 대해서만 살펴보자.

 

<Controller>

@Slf4j
@Controller
@RequestMapping("multipart")
public class TestController {

    //form 호출
    @GetMapping("/create")
    public String form() {
        return "form";
    }

    //form data 처리
    @PostMapping("/upload1")
    public String upload(MultipartFile file) throws IOException {
        printFileInfo(file);
        return "form";
    }

    //MultipartFile 출력
    private void printFileInfo(MultipartFile file) throws IOException {
        log.info("====================================");
        log.info(file.getClass().toString());
        log.info(file.getName());
        log.info(file.getOriginalFilename());
        log.info(file.getContentType());
        log.info(file.getSize() + "");
        log.info("====================================");
        String path = "파일을 저장할 경로"; //ex /Users/test/Desktop
        String extension = file.getContentType().replaceFirst(".*/", ".");
        file.transferTo(new File(path + "/savedFile" + extension));
        //file.transferTo(new File(path, "savedFile" + extension)); 방법2
    }
}

 

학습이 아직 부족하다고 판단한 메서드는 사용하지 않고 명확한 메서드를 이용해 내용을 출력하였다. File에 대한 설명도 여기선 생략하도록 하자. 단순히 new File(파일명을 포함한 경로) or new File(경로, 파일명)의 형태가 있다고 이해하자.

http://localhost:8080/multipart/create를 주소창에 입력후 파일을 등록하고 업로드해보자. 출력은 다음과 같이 나오게 되고 지정한 경로에 이미지 파일이 생성된 것을 확인할 수 있다. getClass() 메서드를 출력한 결과 StandardMultipartFile 구현체가 사용된 것을 알 수 있다.

 

 

관련 다이어그램을 살펴보자.

 

 

참고자료

- Spring Doc

댓글