11. 파일 업로드

2024. 5. 7. 23:32·Spring/MVC 2

HTML 폼 전송 방식

1) application/x-www-form-urlencoded

2) multipart/form-data

 

파일을 업로드 할 때, 파일은 문자가 아니라 바이너리 데이터로 전송해야 한다.

HTML 폼 데이터를 HTTP Body에 문자로 담아, 서버로 전송하는 1) 방법으로는 전송할 수가 없다.

 

이 문제를 해결하기 위해 HTTP는 2) multipart/form-data 전송 방식을 제공한다.

 

 


 

1. multipart/form-data

multipart/form-data에 대해 가볍게 짚고 넘어가자.

 

일단 이 전송 방식을 사용하기 위해서는 Form 태그에 별도의 enctype="multipart/form-data"를 지정해야 한다.

그러면 Form의 입력 결과로 생성된 HTTP 메시지를 보면 각각의 전송 항목이 아래와 같이 Parts로 분리된다.

 

Content-Disposition 헤더는 각 항목의 '이름'이 적혀 있다.

파일의 경우는 사용자가 '업로드한 파일명'과 Content-type 헤더로 '파일 형식'이 추가되어 있다.

------WebKitFormBoundaryx5AichOPCHpAK24v
Content-Disposition: form-data; name="itemName"

apple
------WebKitFormBoundaryx5AichOPCHpAK24v
Content-Disposition: form-data; name="file"; filename="images_1.png"
Content-Type: image/png

**바이너리 데이터를 문자로 바꾸면서 깨짐**

------WebKitFormBoundaryx5AichOPCHpAK24v--

 


 

 

cf 1. 웹브라우저가 서버에 요청할 때마다, 아래와 같이 서버가 받은 HTTP 요청 메시지를 콘솔에 출력한다.

// 스프링 부트 3.2부터 debug 대신 trace를 사용해야 HTTP 요청 메시지를 확인할 수 있다.
// 큰 용량의 파일 업로드를 테스트 할 때는 바이너리-문자 로그가 많이 남기 때문에 끄는 것이 좋다.
logging.level.org.apache.coyote.http11=trace

 

 

cf 2. 파일 업로드 경로

// 해당 경로에 실제 폴더를 미리 만들어야 한다.
// 마지막 '/' 주의
file.dir = /Users/sun/Desktop/Spring/file/

 

 

cf 3. 파일 업로드 사이즈 제한

// max-file-size: 파일 하나의 최대 사이즈. 기본 1MB
// max-request-size: multipart 요청 하나에 여러 파일을 업로드 할 수 있는데, 그 전체 합. 기본 10MB
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB

 

 

cf 4. multipart 요청 처리 off

// default = true
spring.servlet.multipart.enabled=false

 

 


 

2. 스프링 파일 업로드

 

[SpringUploadController]

file.getOriginalFilename() : 업로드 파일명

file.transfetTo(new File(...)) : 파일을 특정 위치로 저장

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

    // application.properties에서 설정한 file.dir 주입
    @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";
    }

}

 

 


 

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

1) 요구사항

1. 상품 관리

     - 이름

     - 첨부 파일 1개

     - 이미지 파일 n개

 

2. 첨부파일을 업로드, 다운로드 할 수 있다.

 

3. 업로드 한 이미지를 웹 브라우저에서 확인할 수 있다.

 

 

2) Domain

[Item]

@Data
public class Item {

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

 

[UploadFile]

서로 다른 고객이 같은 파일 이름을 업로드 하는 경우 기존 파일 이름과 충돌이 날 수 있으므로, 별도의 파일명으로 저장한다.

@Data
public class UploadFile {

    private String uploadFileName; // 고객이 업로드 한 파일명
    private String storeFileName; // 서버 내부에서 관리하는 파일명

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

}

 

 

 

3) Component

[FileStore]

@Component
@RequiredArgsConstructor
public class FileStore {
    private final ItemRepository itemRepository;

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

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

    // 1개의 파일 저장
    public UploadFile storeFile(MultipartFile file) throws IOException {
        if (file == null) {
            return null;
        }

        String originalFilename = file.getOriginalFilename(); // 업로드 파일명
        String storeFileName = createStoreFileName(originalFilename); // 서버에 저장하는 파일명

        file.transferTo(new File(getFullPath(storeFileName)));

        return new UploadFile(originalFilename, storeFileName);
    }

    // 여러 개의 파일 저장
    public List<UploadFile> storeFiles(List<MultipartFile> files) throws IOException {
        List<UploadFile> storeFileResult = new ArrayList<>(); // 계속 생성되는 uploadFile을 리스트로 담아줘야 한다.

        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                UploadFile uploadFile = storeFile(file);
                storeFileResult.add(uploadFile);
            }
        }

        return storeFileResult;
    }

    // 서버에 저장하는 파일명을 랜덤으로 생성
    private static String createStoreFileName(String originalFilename) {
        String uuid = UUID.randomUUID().toString();
        String ext = extractExt(originalFilename);
        return uuid + "." + ext;
    }

    // 파일 확장자를 뒤에 붙인다. (ex> ".jpg")
    private static String extractExt(String originalFilename) {
        int pos = originalFilename.lastIndexOf(".");
        String ext = originalFilename.substring(pos + 1); // 확장자

        return ext;
    }

}

 

 

3) Controller + Service

[ItemController]

@Slf4j
@Controller
@RequiredArgsConstructor
public class ItemController {

    private final ItemRepository itemRepository;
    private final FileStore fileStore;

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


    // 파일은 DB에 저장하는 것이 아니라, storage에 저장한다. (AWS 같은 경우는 S3)
    // DB에 저장하는 것은 파일이 저장된 경로만 저장하면 된다.
    // full path 보다는 base를 설정해두고 그 이후에 상대적인 경로들만 저장한다.
    @PostMapping("/items/new")
    public String saveItem(@ModelAttribute ItemForm form, RedirectAttributes redirectAttributes) throws IOException {
        MultipartFile attachFile = form.getAttachFile();
        List<MultipartFile> imageFiles = form.getImageFiles();

        UploadFile uploadFile = fileStore.storeFile(attachFile);
        List<UploadFile> uploadFiles = fileStore.storeFiles(imageFiles);

        // 데이터베이스 저장
        Item item = new Item();
        item.setItemName(form.getItemName());
        item.setAttachFile(uploadFile);
        item.setImageFiles(uploadFiles);
        itemRepository.save(item);

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

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


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

        return "item-view";
    }


    // 내부 파일에 접근해서 이미지를 다운로드
        // <img> 태그로 이미지를 조회할 때 사용한다.
        // UrlResource로 이미지 파일을 읽어서 @ResponseBody로 이미지 바이너리를 반환한다.
    @ResponseBody
    @GetMapping("/images/{filename}")
    public Resource downloadImage(@PathVariable String filename) throws MalformedURLException {
        // "file:/Users/.../uuid.png"
        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 storeFileName = item.getAttachFile().getStoreFileName();
        String uploadFileName = item.getAttachFile().getUploadFileName();

        UrlResource urlResource = new UrlResource("file:" + fileStore.getFullPath(storeFileName));

        log.info("uploadFileName={}", uploadFileName);

        // 이 속성이 없으면 다운로드가 되지 않고 브라우저에서 보여지기만 한다.
        UriUtils.encode(uploadFileName, StandardCharsets.UTF_8);
        // 고객이 업로드한 파일 이름으로 다운로드 하게 한다.
        String contentDisposition = "attachment; filename=\"" + uploadFileName + "\"";


        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                .body(urlResource);
    }

}
저작자표시

'Spring > MVC 2' 카테고리의 다른 글

10. 스프링 타입 컨버터  (0) 2024.05.06
9. API 예외 처리  (0) 2024.05.06
8. 예외 처리와 오류 페이지  (0) 2024.05.05
7. 로그인 처리2 - 필터, 인터셉터  (0) 2024.05.04
6. 로그인 처리1 - 쿠키, 세션  (1) 2024.05.02
'Spring/MVC 2' 카테고리의 다른 글
  • 10. 스프링 타입 컨버터
  • 9. API 예외 처리
  • 8. 예외 처리와 오류 페이지
  • 7. 로그인 처리2 - 필터, 인터셉터
wch_t
wch_t
  • wch_t
    끄적끄적(TIL)
    wch_t
  • 글쓰기 관리
  • 전체
    오늘
    어제
    • 분류 전체보기 (168)
      • Architecture (0)
      • Algorithm (67)
        • Math (5)
        • Simulation (1)
        • Data Structure (4)
        • DP (7)
        • Brute Fource (10)
        • Binary Search (6)
        • Greedy (2)
        • Graph (11)
        • Mst (1)
        • Shortest path (10)
        • Two Pointer (1)
        • Tsp (3)
        • Union Find (2)
        • Mitm (1)
      • CS (2)
        • 데이터베이스 (5)
        • 네트워크 (5)
      • DB (6)
      • DevOps (15)
        • AWS (9)
        • Docker (1)
        • CI-CD (5)
      • Error (1)
      • Project (0)
        • kotrip (0)
      • Spring (59)
        • 끄적끄적 (5)
        • 기본 (9)
        • MVC 1 (7)
        • MVC 2 (11)
        • ORM (8)
        • JPA 1 (7)
        • JPA 2 (5)
        • Spring Data Jpa (7)
      • Test (2)
      • TIL (5)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    view algorithm
    docker
    apache poi
    form_post
    scope
    spring-cloud-starter-bootstrap
    response_mode
    docker: not found
    백준 17299 파이썬
    백준 3015 파이썬
    Merge
    Sxssf
    애플
    spring-cloud-starter-aws-secrets-manager-config
    Jenkins
    TempTable
    aws secrets manager
    백준 17289 파이썬
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
wch_t
11. 파일 업로드
상단으로

티스토리툴바