반응형
05-14 05:47
Today
Total
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
관리 메뉴

개발하는 고라니

[Spring] 업로드한 파일의 Content-Type 본문

Framework/Spring

[Spring] 업로드한 파일의 Content-Type

조용한고라니 2021. 2. 25. 15:14
반응형

첨부파일을 다루다 보면, 파일의 종류, 확장자에 따라 다르게 처리해야할 경우가 있다. 이 때 업로드된 파일의 종류를 알아보려면 Content-Type이 무엇인지 알면 간단하게 판단할 수 있다.

Content-Type

서버와 클라이언트가 어떤 자원(파일,문서,데이터 등)을 주고받을 때 웹 서버는 HTTP헤더로 파일이나 자원을 포함하는 바이트의 Stream을 앞에 보낸다. 이런 헤더는 클라이언트에게 웹 서버와 커뮤니케이션 세부사항을 묘사한다. 예를 들어, 헤더는 사용되고 있는 웹 서버의 '소프트웨어의 타입', '서버의 날짜와 시간', 'HTTP 프로토콜', '사용중인 커넥션 타입' 등을 지정한다. 헤더는 또한 클라이언트가 이런 가상 패스나 도메인에 대해 저장해야할 쿠키를 포함한다.

 

Content-Type 개체 헤더는 리소스의 Media Type을 나타내기 위해 사용된다.  Media Type = MIME Type이다. 과거에는 MIME(Multipurpose Internet Mail Extension)으로 불렸지만 요즘은 Media Type이라고 한다.

 

(Request/Response 헤더의 모양)

출처: jch9537님의 velog

 

Response 안에 "Content-Type" 헤더는 클라이언트에게 반환된 컨텐츠의 컨텐츠 유형이 실제로 무엇인지 알려준다. 

 

만약 Content(예를 들어 파일)가 image파일이면

Content-Type: image/png
Content-Type: image/jpeg
Content-Type: image/gif
Content-Type: image/webp

등과 같은 타입을 갖으며,

 

<form>태그에서 파일을 업로드하는 형태의 컨텐트 타입은

Content-Type: multipart/form-data

와 같은 형태를 갖는다.

 

이외에도

Content-Type: text/html; charset=utf-8

Content-Type: application/javascript
Content-Type: text/javascript
Content-Type: application/ecmascript
Content-Type: text/ecmascript

과 같은 다양한 MIME type이 있다.

# Multipart로 받은 파일의 Content-Type이 image인지 확인하기

        for(MultipartFile file : uploadFiles){
            String uploadPath = "C:\\upload";
            String originalName = file.getOriginalFilename();
            String fileName = originalName.substring(originalName.lastIndexOf("\\") + 1);

            log.info("File Name : " + fileName);

            String savefileName = uploadPath + fileName;

            Path savePath = Paths.get(savefileName);

            try {
                log.info(Files.probeContentType(savePath).startsWith("image")); //image이면 true를 반환
                log.info(Files.probeContentType(savePath)); //savePath의 MIME를 문자열로 반환
                
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(savePath.toFile()));
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

 

# References

jch9537님의 velog

juyoung님의 블로그

developer.mozilla.org/ko/docs/Web/HTTP/Headers/Content-Type

 

반응형
Comments