Notice
Recent Posts
Recent Comments
Link
반응형
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 스텍
- 알고리즘
- 코딩
- AtoZ0403
- 코딩테스트
- spring
- js
- javascript
- 코테준비
- array
- 카카오
- 배열
- 중간 평균값 구하기
- mybatis
- 백준
- 코테
- 자바
- 그리디알고리즘
- 정렬
- 자바스크립트
- 콜백지옥
- NestJS
- stack
- 인프런
- SWEA
- 프로그래머스
- java
- 자료구조
- 삼성소프트웨어아카데미
- 삼성
Archives
- Today
- Total
개발에 AtoZ까지
[Spring] 파일 단일/다중 업로드(Multipart) 본문
반응형
Spring 환경에서의 파일 업로드 방법에 대해 공유드립니다.
1. POM.xml
파일업로드를 위해 maven에 파일업로드 라이브러리 추가
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
2. web.xml
Spring Security와 Multipart 사용시에는 Multipart 필터를 Spring Security 앞에 설정해줘야한다.
안그러면 Multipart 필터가 정상적으로 동작하지 않는 현상 발생
<filter>
<description>스프링 파일업로드 필터 등록-스프링시큐리티설정전에 위치해야 한다</description>
<filter-name>MultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MultipartFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter>
<description>스프링 시큐리티 필터 등록</description>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
3. servlet-context.xml
CommonsMultipartResolver bean 등록, CommonsMultipartResolver 옵션은 아래와 같다.
Property | Type | Description |
maxUploadSize | Long | 최대 업로드 가능한 바이트 크기, -1은 제한이 없음을 의미합니다. Default(-1) |
maxInMemorySize | int | 디스크에 임시 파일을 생성하기 전에 메모리에 보관할 수 있는 최대 바이트 크기, 기본 값은 10240 바이트입니다. |
defaultEncording | String | 요청을 파싱할 때 사용할 캐릭터 인코딩, 지정하지 않은 경우 HttpServletRequest.setEncording() 메서드로 지정한 캐릭터 셋이 사용됩니다. 아무 값도 없을 경우 ISO-8859-1을 사용합니다. |
<!--파일업로드 설정(multiparts) -->
<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 파일업로드 크기 20MB로 설정 -->
<property name="maxUploadSize" value="209715200"/>
</bean>
4. WAS 설정(context.xml)
WAS(Tomcat)/ config/context.xml에 <context>에 아래와 같이 변경한다.
만약 WAS에 아래와 같이 설정하지 않으면 "Could not parse multipart servlet request" 에러발생, WAS에서 Multipart를 찾지 못하게 된다.
<Context allowCasualMultipartParsing="true" >
5. JSP 소스
1) 단일 파일
Multipart 사용시에는 enctype="multipart/form-data" 속성을 사용해줘야 한다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>파일업로드</title>
</head>
<body>
<form name="fileForm" action="fileupload1" method="post" enctype="multipart/form-data">
<sec:csrfInput/>
<input type="file" name="file" />
<input type="submit" value="전송" />
</form>
</body>
</html>
2) 다중 파일
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>파일업로드</title>
</head>
<body>
<form name="fileForm" action="fileupload1" method="post" enctype="multipart/form-data">
<sec:csrfInput/>
<input multiple="multiple" type="file" name="picFile" required="required">
<input type="submit" value="전송" />
</form>
</body>
</html>
6. Controller 소스
1) 단일파일
@RequestMapping(value = "fileupload1")
public String requestupload1(MultipartHttpServletRequest mRequest) {
String src = mRequest.getParameter("src");
MultipartFile mf = mRequest.getFile("file");
String path = "C:\\image\\";
String originFileName = mf.getOriginalFilename(); // 원본 파일 명
long fileSize = mf.getSize(); // 파일 사이즈
System.out.println("originFileName : " + originFileName);
System.out.println("fileSize : " + fileSize);
String safeFile = path + originFileName;
try {
mf.transferTo(new File(safeFile));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:/";
}
2) 다중파일
@RequestMapping(value = "fileupload2")
public String requestupload2(MultipartHttpServletRequest mRequest) {
List<MultipartFile> fileList = mRequest.getFiles("file");
String src = mRequest.getParameter("src");
String path = "C:\\image\\";
for (MultipartFile mf : fileList) {
String originFileName = mf.getOriginalFilename(); // 원본 파일 명
long fileSize = mf.getSize(); // 파일 사이즈
System.out.println("originFileName : " + originFileName);
System.out.println("fileSize : " + fileSize);
String safeFile = path + originFileName;
try {
mf.transferTo(new File(safeFile));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "redirect:/";
}
반응형
'백엔드 > Spring' 카테고리의 다른 글
[에러]Database "mem:testdb" not found, either pre-create it or allow remote database creation (0) | 2021.07.19 |
---|---|
[Spring Boot] Gradle로 Build하는 방법 (0) | 2021.06.13 |
[에러] Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 39; 예기치 않은 파일의 끝입니다. (0) | 2021.05.26 |
[Spring Boot] 전송방식에 따른 Parameter 받는 방법 (1) | 2021.04.30 |
H2, JPA, MyBatis 특징 및 차이 (0) | 2021.01.17 |
[Spring] Mybatis 와 JPA 환경설정 차이 (0) | 2021.01.17 |
Comments