둘셋 개발!

[spring mvc 2편-웹 개발 활용 기술 - 9 ] 파일 업로드 본문

SPRING/MVC

[spring mvc 2편-웹 개발 활용 기술 - 9 ] 파일 업로드

23 2022. 3. 8. 15:56

이번 포스팅에서는 파일을 업로드를 어떻게 하는것인가!  업로드 말고도 업로드를 했던 파일을 다시 다운로드 받는 방법도 알아볼 것이다

 


  HTML 폼 전송 방식

 

1. application/x-www-form-urlencoded : http body에 문자를 전송
2. multipart/form-data : http body에 문자와 바이너리 데이터(파일) 전송

 

1. application/x-www-form-urlencoded

➡️ form태그에 별도의 enctype옵션이 없으면 웹브라우저는 요청 http 헤더에 Content-Type: application/x-www-form-urlencodeded를 추가

➡️그리고 http 메세지 바디에는 전송할 데이터를 &로 구분하여 전송

 

 

2. multipart/form-data 

➡️ form 태그에 별도의 enctype="multipart/form-data"를 지정해야 다른 종류의 여러 파일과 폼의 내용을 전송할 수 있다.

➡️ 웹 브라우저가 생성한 요청 http 메세지를 보면 Content-Disposition으로 전송할 데이터가 구분되어 있다.

➡️ 파일의 경우 Content-Type이 추가되고 그 밑에는 바이너리 데이터가 들어간다.

 

이제 이렇게 웹 브라우저가 생성산 요청 http 메세지를 서버가 어떻게 읽고 사용하는지 알아볼 것이다!

 


서블릿을 통한 파일업로드

 

스프링을 사용하지 않고 서블릿으로만 파일을 업로드할 때 어떻게 동작하는지 알아보자

 

- request.getParts()

@Slf4j
@Controller
@RequestMapping("/servlet/v1")
public class ServletUploadControllerV1 {

    @GetMapping("/upload")
    public String newFile(){
        return "upload-form";
    }

    @PostMapping("/upload")
    public String saveFileV1(HttpServletRequest request) throws ServletException, IOException {
        log.info("request={}", request);

        String itemName = request.getParameter("itemName");
        log.info("itemName={}",itemName);

        Collection<Part> parts = request.getParts();
        log.info("parts={}", parts);

        return "upload-form";
    }

}

➡️ request.getParts()를 사용하면 multipart/form-data 전송 방식에서 각각 나누어진 부분을 받아서 확인 할 수 있다.

(이렇게 받아온 parts의 대해서는 뒤에 설명할 것이다. )

 

 

위의 결과를 보면

➡️ HttpServletRequest 객체가 RequestFacade 에서 StandardMultipartHttpServletRequest로 변한 것을 확인할 수 있다

사실 이것은 spring.servlet.multipart.enabled라는 옵션이 true이기 때문에 변한 것이다.

이 옵션을 키면 DispatcherServlet에서 MultipartResolver를 실행하고, MultipartResolver는 멀티파트의 요청일 경우 일반적인 HttpServletRequest를 MultiPartServletRequest로 변환한다.

StandardMultipartHttpServletRequest는 MultiPartServletRequest의 구현체이다.

따라서 멀티파트 처리를 하고 싶다면 spring.servlet.multipart.enabled라는 옵션이 true이기만 하면 된다!!(기본이 true임)

 

 

이제부터는 서블릿이 제공하는 Part에 대해 더 알아보고 실제 파일을 업로드 해볼 것이다.

우선 업로들 할 실제 파일을  저장할 폴더의 경로를 입력해야한다.

application.propterties에 다음과 같이 입력한다.

file.dir= 파일 경로        예)   /Users/janguni/study/upload_file/
@Slf4j
@Controller
@RequestMapping("/servlet/v2")
public class ServletUploadControllerV2 {

    @Value("${file.dir}")   //application-properties 에 있는 값을 불러올 수 있음
    private String fileDir;

    @GetMapping("/upload")
    public String newFile(){
        return "upload-form";
    }

    @PostMapping("/upload")
    public String saveFileV2(HttpServletRequest request) throws ServletException, IOException {
        log.info("request={}", request);

        String itemName = request.getParameter("itemName");
        log.info("itemName={}",itemName);

        Collection<Part> parts = request.getParts();
        log.info("parts={}", parts);

        for (Part part : parts) {

            log.info("=== PART ===");
            log.info("name={}",part.getName());
            Collection<String> headerNames = part.getHeaderNames();
            for (String headerName : headerNames) {
                log.info("header {}: {}", headerName, part.getHeader(headerName));
            }

            // 편의 메서드
            // content-disposition; filename
            log.info("submittedFileName={}",part.getSubmittedFileName());
            log.info("size={}", part.getSize()); //part body size

            //데이터 읽기
            InputStream inputStream = part.getInputStream();
            String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
            log.info("body={}", body);

            //파일에 저장
            if (StringUtils.hasText(part.getSubmittedFileName())){
                String fullPath = fileDir + part.getSubmittedFileName();
                log.info("파일 저장 fullPath={}", fullPath);
                part.write(fullPath);
            }
        }

        return "upload-form";
    }

}

위의 컨트롤러에서는 parts에 담긴 part를 Iter로 돌려서 각 part의

 

➡️ headerName, header값

➡️ submittedFileName(클라이언트가 전달한 파일명) 값, bodysize 값

➡️ body 내용

➡️ 실제 파일을 저장한 경로

 

를 로그로 찍어 보았다.

➡️ 마지막에 part.write("실제 파일을 저장할 경로")를 함으로써 파일을 저장했다!!

 

✔️Part의 주요 메서드

- part.getSebmittedFileName() : 클라이언트가 전달한 파일명
- part.getInputStream() : Part의 전송 데이터를 읽어들임
- part.write() : Part를 통해 전송된 데이터를 저장!!

 

이제 스프링으로 더 편하게 파일을 업로드 해보자!

 


스프링을 통한 파일 업로드

스프링은 MultipartFile이라는 인터페이스를 통해 멀티파트 파일을 편리하게 지원한다.

@Slf4j
@Controller
@RequestMapping("/spring")
public class SpringUploadController {

    @Value("${file.dir}")
    private String fileDir;

    @GetMapping("/upload")
    public String newFile(){
        return "upload-form";
    }

    @PostMapping("/upload")
    public String saveFile(@RequestParam String itemName,
                           @RequestParam MultipartFile file, HttpServletRequest request) throws IOException {

        log.info("request={}",request);
        log.info("itemName={}",itemName);
        log.info("multipartFile={}", file);

        if(!file.isEmpty()){
            String fullPath = fileDir + file.getOriginalFilename();
            log.info("파일 저장 fullPath={}", fullPath);
            file.transferTo(new File(fullPath));
        }


        return "upload-form";
    }
}

➡️ @RequestParam MultipartFile file 에서는 html 폼에 있는 name에 맞춰서 변수명을 적으면 된다!

➡️ file.getOriginalFilename()에서는 클라이언트가 업로드한 파일명이다.

➡️ file.trasfetTo()를 통해 파일을 저장한다!

 

* upload-form.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
</head>
<body>
<div class="container">
    <div class="py-5 text-center"> <h2>상품 등록 폼</h2>
    </div>
    <h4 class="mb-3">상품 입력</h4>
    <form th:action method="post" enctype="multipart/form-data">
        <ul>
            <li>상품명 <input type="text" name="itemName"></li>
            <li>파일<input type="file" name="file" ></li> </ul>
        <input type="submit"/>
    </form>
</div> <!-- /container -->
</body>
</html>

 

✔️MultipartFile 주요 메서드

- file.getOriginalFilename() : 클라이언트가 업로드한 파일명
- file.transferTo() : 파일을 저장함

 

이제부터는 실제로 파일을 업로드할 때 고려해야 할 사항들을 알아보고, 업로드된 파일을 웹브라우저에서 확인해보고, 업로드한 파일을 다운로드 해볼 것이다.

 


예제로 구현하는 파일 업로드, 다운로드

업로드한 파일을 데이터베이스에 저장하고 지정한 경로로 파일을 다운받고 다시 고객이 파일을 다운받을 수 있도록 한다

 

1. 우선 상품 도메인과 상품 레포지토리를 만든다

-상품 도메인

@Data
public class Item {

    private Long id;
    private String itemName;
    private UploadFile attachFile;
    private List<UploadFile> imageFiles;
}

-상품 레포지토리

@Repository
public class ItemRepository {

    private final Map<Long, Item> store = new HashMap<>();
    private long sequence = 0L;

    public Item save(Item item){
        item.setId(++sequence);
        store.put(item.getId(),item);
        return item;
    }

    public Item findById(Long id){
        return store.get(id);
    }
}

 

2. 업로드 파일 정보를 보관한다

서버 내부에 파일을 저장할 때 고객이 작성한 파일명을 그대로 사용하면 안된다. 서로 다른 고객이 같은 파일명을 적을 수도 있기 때문에, 서버 내부에서 별도로 파일명을 관리 해야 한다.

@Data
public class UploadFile {

    private String uploadFileName; //클라이언트가 저장한 파일이름
    private String storeFileName; //서버 내부에서 관리하는 파일이름

    public UploadFile(String uploadFileName, String storeFileName) {
        this.uploadFileName = uploadFileName;
        this.storeFileName = storeFileName;
    }
}

 

3. 파일 저장과 관련된 업무 처리

package hello.upload.file;


import hello.upload.domain.UploadFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Component
public class FileStore {

    @Value("${file.dir}")
    private String fileDir;

    public String getFullPath(String filename){
        return fileDir + filename;
    }

    //파일들을 저장
    public List<UploadFile> storeFiles(List<MultipartFile> multipartFiles) throws IOException {
        List<UploadFile> storeFileResult = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            if(!multipartFile.isEmpty()){
                storeFileResult.add(storeFile(multipartFile));
            }
        }
        return storeFileResult;
    }

    //파일을 저장
    public UploadFile storeFile(MultipartFile multipartFile) throws IOException {
        if (multipartFile.isEmpty()){
            return null;
        }

        //고객이 저장한 파일이름이 아닌 서버 내부에서 관리하는 파일이름이름으로 저장
        String originalFilename = multipartFile.getOriginalFilename();
        String storeFileName = createStoreFileName(originalFilename);
        multipartFile.transferTo(new File(getFullPath(storeFileName)));
        return new UploadFile(originalFilename, storeFileName);
    }

    private String createStoreFileName(String originalFilename) {
        String ext = extractExt(originalFilename);
        String uuid = UUID.randomUUID().toString();
        return uuid + "." + ext;
    }

    private String extractExt(String originalFilename) {
        int pos = originalFilename.lastIndexOf(".");
        return originalFilename.substring(pos + 1);
    }


}

➡️ storeFile : 고객이 작성한 파일명과 서버내부에서 관리할 파일명을 만들고, 서버내부에서 관리할 파일명으로 실제 파일을 저장한다

➡️ storeFiles :  여러개의 파일을 저장한다

 

4. 상품 컨트롤러

@Slf4j
@Controller
@RequiredArgsConstructor
public class ItemController {

    private final ItemRepository itemRepository;
    private final FileStore fileStore;

    @GetMapping("/items/new")
    public String newItem(@ModelAttribute ItemForm itemForm){
        return "item-form";
    }

    @PostMapping("/items/new")
    public String saveItem(@ModelAttribute ItemForm itemForm, RedirectAttributes redirectAttributes) throws IOException {
        UploadFile attachFile = fileStore.storeFile(itemForm.getAttachFile());
        List<UploadFile> storeImageFiles = fileStore.storeFiles(itemForm.getImageFiles());

        //데이터 베이스에 저장
        //파일 자체를 저장하는 것이 아니라 파일이름만 저장
        Item item = new Item();
        item.setItemName(itemForm.getItemName());
        item.setAttachFile(attachFile);
        item.setImageFiles(storeImageFiles);
        itemRepository.save(item);

        redirectAttributes.addAttribute("itemId", item.getId());

        return "redirect:/items/{itemId}";
    }

    @GetMapping("/items/{id}")
    public String items(@PathVariable Long id, Model model){
        Item item = itemRepository.findById(id);
        model.addAttribute("item",item);
        return "item-view";
    }

    //고객이 업로드한 이미지 화면에 출력
    @ResponseBody
    @GetMapping("/images/{filename}")
    public Resource downloadImage(@PathVariable String filename) throws MalformedURLException {
        return new UrlResource("file:" + fileStore.getFullPath(filename));
    }

    //고객이 업로드한 파일을 다시 다운로드 받기
    @GetMapping("/attach/{itemId}")
    public ResponseEntity<Resource> downloadAttach(@PathVariable Long itemId) throws MalformedURLException {
        Item item = itemRepository.findById(itemId);
        String uploadFileName = item.getAttachFile().getUploadFileName();
        String storeFileName = item.getAttachFile().getStoreFileName();
        UrlResource resource = new UrlResource("file:" + fileStore.getFullPath(storeFileName));

        log.info("uploadFileName={}", uploadFileName);
        String encodeUploadFileName = UriUtils.encode(uploadFileName, StandardCharsets.UTF_8);
        String contentDisposition = "attachment; filename=\"" + encodeUploadFileName + "\"";
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                .body(resource);
    }
}

➡️ saveItem() : 데이터 베이스에 item 저장

파일을 가져옴 -> UploadFile로 바꿈(업로드한 파일명, 서버내부에서 저장할 파일명) -> 데이터 베이스에 저장(item객체 생성후 item 레포지토리에 저장)

 

➡️ downloadImage() : 웹 브라우저에 이미지 보여주기

파일이름을 가져옴 -> 파일이 저장된 경로 가져오기 -> 실제 파일을 브라우저에 보여주기: UrlResource로 이미지 파일을 읽어서 @ResponseBody로 이미지 바이너리를 반환

 

➡️ downloadAttach() : 업로드된 파일을 불러와서 다운로드 할 수 있게 함

item의 id를 가지고 실제 파일을 가져오기(resource) -> Content-Disposition헤더에 attachment; filename="업로드 파일명"값을 넣어줌, 바디에는 resource 넣어주기 

여기서 resource의 파일명은 고객이 업로드한 파일명을 써주는 것이 좋다

 

끝!

(참고 : 인프런 김영한 강사님 - 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 )