Spring/[인프런 김영한 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술]

[인프런 김영한 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술] 파일 업로드

h2boom 2024. 11. 11. 16:40

파일 업로드

  • HTML Form을 전송하는 방식
    • application/x-www-form-urlencoded
    • multipart/form-data

application/x-www-form-urlencoded 방식

  • application/x-www-form-urlencoded 방식 : Form 태그에 별도의 enctype 옵션이 없는 경우의 Content-Type
    • Form에 입력한 전송할 항목을 HTTP Body에 문자로 전송해주며 &로 구분한다.
    • 파일 업로드의 경우 문자가 아닌 바이너리 데이터를 전송해야하기에 이 방식은 적절하지 않다.


Multipart/form-data 방식

  • multipart/form-data 방식 : Form 태그에 별도의 enctype="multipart/form-data"를 지정하는 경우
    • 다른 종류의 여러 파일과 Form의 내용을 함께 전송할 수 있다.
    • 전송 항목이 각각 구분되어 있다.
    • Content-Disposition이라는 항목별 헤더와 부가 정보가 있다.

 

  • application.properties에서 설정을 통해 업로드 사이즈 제한을 할 수 있다.
//파일 업로드 사이즈 설정
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB

//멀티 파트 제한 설정
spring.servlet.multipart.enabled=false

//파일 업로드 경로 설정
file.dir=/~/경로/
  • 파일 업로드 관련 application.properties 설정
    • 업로드 사이즈 제한을 할 수 있다.
    • 서블릿 컨테이너가 multipart와 관련된 처리를 하지 않도록 제한할 수 있다. (기본값 true)
    • 파일 업로드 경로를 설정할 수 있으며 마지막은 무조건 /가 와야한다.

 

@Slf4j
@Controller
@RequestMapping("/servlet/v2")
public class ServletUploadControllerV2 {

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

    @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());

            //데이터 읽기
            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";
    }
}
  • 파일 업로드 예제
    • @Value로 application.properties에서 설정한 file.dir의 값을 주입받을 수 있다.
    • multipart 형식이므로 전송 데이터 하나하나가 각 Part로 나눠 전송된다.
  • Part 주요 메소드
    • getSubmittedFileName() : 클라이언트가 전달한 파일명
    • getInputStream() : Part의 전송 데이터를 읽을 수 있다.
    • write() : Part를 통해 전송된 데이터를 저장할 수 있다. (파일도 포함)

 

  • 큰 용량의 파일을 업로드하는 경우 로그가 너무 많이 남으면 성능에 문제가 생긴다.

스프링과 파일 업로드

  • 스프링에서 MultipartFile 인터페이스로 멀티파트 파일을 매우 편리하게 지원한다.

 

@Slf4j
@Controller
@RequestMapping("/spring")
public class SpringUploadController {
    @Value("${file.dir}")
    private String fileDir;

    @PostMapping("/upload")
    public String saveFile(@RequestParam("itemName") String itemName,
                           @RequestParam("file") 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";
    }
}
  • 스프링에서 파일 업로드 예제
    • MultipartFile을 사용해 @RequestParam, @ModelAttribute로도 multipart 파일에 적용할 수 있다.
  • MultipartFile 주요 메소드
    • getOriginalFilename() : 업로드 파일명
    • transferTo() : 파일 업로드(저장)

예제를 통한 파일 업로드 / 다운로드

  • 주의할 점
    • 기존 파일과 겹칠 수 있기에 고객이 업로드한 파일명으로 서버 내부에 파일을 저장해서는 안된다. 
      • 서버 내부에서 관리하는 별도의 파일명으로 저장해야 한다.

 

@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();
        //image.png -> png

        //서버에 저장하는 파일명 + 기존 파일의 확장자명
        String storeFileName = createStoreFileName(originalFilename);
        multipartFile.transferTo(new File(getFullPath(storeFileName)));

        return new UploadFile(originalFilename, storeFileName);
    }

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

    private String extractExt(String originalFilename) {
        int pos = originalFilename.lastIndexOf(".");
        return originalFilename.substring(pos + 1);
    }
}
  • 파일 저장과 관련된 기능
    • extractExt()는 서버에 저장하는 파일명을 별도로 만들때 기존 파일의 확장자 명을 추출하기 위한 메소드이다.
    • createStoreFileName()은 기존 파일명을 서버에 저장할 때 파일명이 겹치지 않도록 UUID를 생성하고 확장자를 합쳐서 새로운 파일명을 만들기 위한 메소드이다.

 

  • 실제 파일은 스토리지에 저장하고 DB에는 path만 저장한다.
    • ex) DB에 파일 path만 저장하고 AWS S3 스토리지에 실제 파일 저장

 

@Slf4j
@Controller
@RequiredArgsConstructor
public class ItemController {
    private final ItemRepository itemRepository;
    private final FileStore fileStore;

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

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

        //데이터베이스에 저장
        Item item = new Item();
        item.setItemName(form.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("id") Long id, Model model) {
        Item item = itemRepository.findById(id);
        model.addAttribute("item", item);

        return "item-view";
    }

    @ResponseBody
    @GetMapping("/images/{filename}")
    public Resource downloadImage(@PathVariable("filename") String filename) throws MalformedURLException {
        //해당 경로의 파일을 스트림으로 반환
        return new UrlResource("file:" + fileStore.getFullPath(filename));
    }

    @GetMapping("/attach/{itemId}")
    public ResponseEntity<Resource> downloadAttach(@PathVariable("itemId") Long itemId) throws MalformedURLException {
        Item item = itemRepository.findById(itemId);
        String storeFileName = item.getAttachFile().getStoreFileName();
        String uploadFileName = item.getAttachFile().getUploadFileName();

        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()에서 RedirectAttributes는 redirect 시 PathVariable 처럼 itemId를 사용하기 위함
    • downloadImage()에서 UrlResource 클래스를 사용함으로 해당 경로의 파일을 스트림으로 반환해준다.
      • 형식 = file:/파일전체경로/
      • UrlResource 방식 외에도 여러가지 방식이 존재한다.
    • downloadAttach()에서 itemId를 사용한 이유는 해당 Item의 권한이 있는 사용자만 다운로드 할 수 있게 하기 위함 (현 예제에서는 인증 로직이 따로 없으며 하나의 예시일 뿐)
      • 파일을 다운로드 받기 위해서 CONTENT_DISPOSITION 헤더를 추가해야하는 규약이 있기에 필수로 추가해줘야 한다. 
        • 한글, 특수문자가 깨질 수 있기에 UrlUtils.encode()로 파일명을 인코딩 후 인코딩 된 파일명을 넣어줘야 한다.
        • 헤더가 없으면 파일을 다운로드 받지 않고 파일의 내용만 읽어오게 된다.

정리

  • 여러 종류의 파일을 업로드하기 위해서는 Form 태그에 별도의 enctype="multipart/form-data"를 지정해야 한다.
  • 스프링 사용 시 멀티파트를 지원하는 MultipartFile을 사용하면 된다.
  • 업로드 파일명과 별도로 서버 내부에서 관리하기 위한 파일명을 관리해야 한다.
  • DB에는 파일 Path만 저장하고 스토리지에 실제 파일을 저장하는 형식으로 사용한다.
  • 파일을 다운로드 받기 위해서 CONTENT_DISPOSTION 헤더를 필수로 추가해줘야 한다.

출처 : [인프런 김영한 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술]

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-2/dashboard

 

스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 강의 | 김영한 - 인프런

김영한 | 웹 애플리케이션 개발에 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. MVC 2편에서는 MVC 1편의 핵심 원리와 구조 위에 실무 웹 개발에 필요한 모든 활용 기술들을 학습

www.inflearn.com