파일 업로드 시 가장 많이 사용하는 기능이 멀티파트 입니다.
스프링 MVC도 멀티파트 기능을 지원하기 때문에 이를 이용해서 업로드를 구현합니다.
파일 업로드
파일을 웹 브라우저에서 서버로 전송하여 저장하는 것을 말합니다.
서버로 전송할 수 있는 파일은 텍스트 파일, 바이너리 파일, 이미지 파일 등이 있습니다.
웹에서 서버로 파일을 전송하기 위해서 JSP 페이지에 폼 태그를,
파일을 서버에 저장하기 위해서는 오픈 라이브러리를 사용합니다.
다음은 파일을 업로드하기 위한 환경 설정입니다.
우선 pom.xml 파일에 의존 라이브러리를 등록해줍니다.
<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>
commons-fileupload.jar와 commons-io.jar 파일을 라이브러리로 등록해줍니다.
그 다음은 servlet-context.xml 파일에 시큐리티 필터를 등록해줘야 합니다.
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="100000"/>
<beans:property name="defaultEncoding" value="utf-8"/>
<beans:property name="uploadTempDir" ref="uploadDirResource"/>
</beans:bean>
<beans:bean id="uploadDirResource"
class="org.springframework.core.io.FileSystemResource">
<beans:constructor-arg value="c:/upload/"/>
</beans:bean>
멀티파트 기능을 이용하기 위해서 MultipartResolver를 파일에 등록해줍니다.
업로드할 수 있는 파일 최대 크기, 기본 인코딩, 임시 저장 공간을 설정해줍니다.
파일 업로드를 위한 웹 페이지
웹에서 서버로 파일을 전송하기 위해서는 JSP 페이지가 필요합니다.
이 때 JSP 페이지 폼 태그 작성 시 몇 가지 규칙이 있습니다.
형식은 다음과 같습니다.
<form method="POST" enctype="multipart/form-data">
<input type="file" name="요청 매개변수 이름">
</form>
다음은 JSP 페이지에 파일을 업로드하는 폼 태그 사용 예시입니다.
<%@ page contentType="text/html; charset=utf-8" %>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="process.jsp">
<p>제목 : <input type="text" name="title">
<p>파일 : <input type="file" name="fileName">
<p><input type="submit" value="submit">
</form>
</body>
</html>
<form> 태그의 method 속성은 반드시 POST 방식이어야 합니다.
<form> 태그의 enctype 속성은 반드시 multipart/form-data로 설정해야 합니다.
<input> 태그의 type 속성은 file로 설정합니다.
파일 여러 개를 업로드하기 위해서는 두 개 이상의 <input> 태그를 사용해야합니다.
이 때 name 속성은 서로 다른 값이어야 합니다.
'SPRING' 카테고리의 다른 글
[SPRING]#29 도서 쇼핑몰 구현 (파일 업로드3) (0) | 2024.01.11 |
---|---|
[SPRING]#28 도서 쇼핑몰 구현 (파일 업로드2) (0) | 2024.01.11 |
[SPRING]#26 도서 쇼핑몰 구현 (스프링 시큐리티8) (0) | 2024.01.11 |
[SPRING]#25 도서 쇼핑몰 구현 (스프링 시큐리티7) (0) | 2024.01.10 |
[SPRING]#24 도서 쇼핑몰 구현 (스프링 시큐리티6) (0) | 2024.01.10 |