[Spring] 스프링에서 파일을 업로드(첨부파일) 하기 위한 라이브러리 2가지

2022. 11. 22. 10:26·📗 self-study/📗 KH정보교육원 당산지원

 

⌛️ 현재 상황

👉🏻  게시글 글을 쓰고 등록하기를 눌러 보면

 

👉🏻  웰컴 투 널 파티 ^^... 심지어 첨부파일은 아무런 내용 없이 그냥 Null이다

 

 

 

🔧 상황 정리

요청 시 name 속성과 필드명을 정확하게 맞췄음에도 불구하고 제대로 된 전달값이 안 들어옴
요청 시 분명히 파일을 넘겼음에도 불구하고 upfile 값이 null
👉🏻  파일 업로드에 필요한 Spring 라이브러리를 pom.xml에 추가하지 않았기 때문
👉🏻  파일 업로드용 라이브러리: commons-fileupload, commons-io

 

 

 

💻 pom.xml 코드 한 눈에 보기

		<!-- 4. 파일 업로드 관련 두 개의 라이브러리 -->
		<dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>1.4</version>
		</dependency>
		
		<dependency>
    		<groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.11.0</version>
		</dependency>

 

💻 root-context.xml 코드 한 눈에 보기

	<!-- 파일 업로드 관련 빈 등록 -->
	<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
		
		<!-- defaultEncoding: 업로드되는 파일에 대한 인코딩 처리를 어떻게 할 건지를 지정 -->
		<property name="defaultEncoding" value="UTF-8" />
		
		<!-- maxUploadSize: 한 번에 업로드되는 파일의 총 용량-->
		<property name="maxUploadSize" value="10000000" />
		
		<!--  maxInMemorySize: 메모리상의 파일 최대 용량, 하나의 파일 최대 용량이 10000000Byte 값으로 지정됨 -->
		<property name="maxInMemorySize" value="10000000" />
		
	</bean>

 

 

 

<다운로드 및 사용 방법 상세 보기>

 

 

 

1. https://mvnrepository.com/ 접속

 

2. commons-fileupload 검색

👉🏻 최신 버전이지만 usages도 꽤 높은 1.4 버전을 다운로드

		<dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>1.4</version>
		</dependency>

 

3. commons-io 검색

👉🏻 최신 버전이면서 usages가 높은 2.11.0 버전 다운로드

👉🏻 두 가지 라이브러리의 버전을 굳이 맞출 필요 없음!

		<dependency>
    		<groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.11.0</version>
		</dependency>

 

4. root-context.xml에 bean 등록하기

⌨️ 이렇게 bean을 등록까지만 한 상태에서는 multipartResolver 객체의 기본 생성자가 만들어진 상태가 됨

	<!-- 파일 업로드 관련 빈 등록 -->
	<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
		
	</bean>

 

✔️ 속성 지정해 주기

👉🏻 defaultEncoding: 업로드되는 파일에 대한 인코딩 처리를 어떻게 할 건지를 지정

 

👉🏻 maxUploadSize: 한 번에 업로드되는 파일의 총 용량


       총 파일의 최대 용량을 10MByte로 지정하고 싶다면,
       10MByte == 10 * 1024 * 1024 Byte
       단, xml에서는 계산식이 적용되지 않으므로 직접 계산한 결과를 넣어야 함


      계산 결과 == 10,485,760 => 대략 10,000,000

       즉, 자바에서는 value="10 * 1024 * 1024"이 자동으로 계산됐지만 스프링에서는 계산된 결과값을 넣어 줘야 함!       

 

👉🏻 maxInMemorySize: 메모리상의 파일 최대 용량, 하나의 파일 최대 용량이 10000000Byte 값으로 지정됨

	<!-- 파일 업로드 관련 빈 등록 -->
	<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
		
        	<property name="defaultEncoding" value="UTF-8" />
		<property name="maxUploadSize" value="10000000" />
		<property name="maxInMemorySize" value="10000000" />
		
	</bean>

 

 

 

 

<결과 화면 확인>

👉🏻 이 과정 이후 게시글과 첨부파일에 대한 정보가 제대로 넘어옴을 확인 가능!


1. 첨부파일이 있을 때 size는 첨부파일의 사이즈로 찍힘

 

1. 첨부파일이 없을 때 때 size는 0으로 찍힘

저작자표시 비영리 변경금지 (새창열림)
'📗 self-study/📗 KH정보교육원 당산지원' 카테고리의 다른 글
  • [Spring] Spring에서 Ajax 사용하기 1 - 기본 설정과 Ajax 사용법 2가지(HttpSession 이용/응답할 데이터를 문자열 타입으로 반환)
  • [Spring] Spring 웹 사이트 만들기 7 - 게시판(쿼리스트링을 숨길 수 있는 게시글 삭제/수정)
  • [Spring] Spring 웹 사이트 만들기 7 - 게시판(게시글 작성/상세 조회)
  • [Spring] Spring 웹 사이트 만들기 6 - 게시판(전체 조회, 페이징 처리)
천재강쥐
천재강쥐
  • 천재강쥐
    디버거도 버거다
    천재강쥐
  • 전체
    오늘
    어제
    • Category (467)
      • 진짜 너무 궁금한데 이걸 나만 몰라...? (0)
      • 💾 Portfolio (2)
      • 🐤 CodingTest (28)
        • Java (20)
        • ᕕ(ꐦ°᷄д°᷅)ᕗ❌ (5)
      • 🚀 from error to study (142)
        • AI (1)
        • Cloud (2)
        • DB (12)
        • Front-End (16)
        • Github (14)
        • Java (39)
        • Mac (7)
        • Normal (29)
        • Server (22)
      • 📘 certificate (44)
        • 📘 리눅스마스터1급 (1)
        • 📘⭕️ 정보처리기사 (40)
        • 📘⭕️ SQLD (3)
      • 📗 self-study (234)
        • 📗 inflearn (35)
        • 📗 생활코딩 (8)
        • 📗 KH정보교육원 당산지원 (190)
      • 🎨 Scoop the others (0)
        • 📖 Peeking into other people.. (0)
        • 🇫🇷 (0)
        • 📘⭕️ 한국사능력검정시험 심화 (11)
        • 오블완 (4)
  • 인기 글

  • hELLO· Designed By정상우.v4.10.1
천재강쥐
[Spring] 스프링에서 파일을 업로드(첨부파일) 하기 위한 라이브러리 2가지
상단으로

티스토리툴바