Spring/코드로 배우는 스프링 웹 프로젝트

파일 업로드 처리 (servlet-context.xml)

하루인생 2021. 2. 23. 20:03

이전에 파일 업로드 처리에 대해 글을 작성한 적이 있다. 

이전에는 java로 설정을 해서 업로드 처리를 했다면 이번에는 servlet-context.xml 파일에 설정을 해보겠다.

(파일 업로드 java설정 링크 :  web-developer-backend.tistory.com/24?category=965354 )

 

 

1) pom.xml 설정

 

commons-fileupload 라이브러리를 설치한다.

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

 

2) servlet-context.xml 설정

 

maxUploadSize : 한번의 request로 전달될 수 있는 최대 크기
maxUploadSizePerFile : 하나의 파일 최대 크기
uploadTempDir : 크기 이상의 데이터는 임시파일에 보관
maxInMemorySize : 메모리상에 유지되는 최대 크기

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<beans:property name="defaultEncoding" value="utf-8"/>
		<beans:property name="maxUploadSize" value="104857560"/>
		<beans:property name="maxUploadSizePerFile" value="2097152"/>
		<beans:property name="uploadTempDir" value="file:/C:/upload/tmp"/>
		<beans:property name="maxInMemorySize" value="04857560"/>
</beans:bean>

 

3) 컨트롤러 설정

@Controller
@RequestMapping("/sample/*")
@Log4j
public class SampleController {
	
	@GetMapping(value = "/exUpload")
	public String exUpload() {
		System.out.println("upload.....");
		return "sample/exUpload";
	}
	
	@PostMapping("/exUploadPost")
	public void exUploadPost(ArrayList<MultipartFile> files) {
		files.forEach(file -> {
			System.out.println("------------------------------");
			System.out.println("name : " + file.getOriginalFilename());
			System.out.println("size : " + file.getSize());
		});
	}
}

 

4) jsp 작성

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="/sample/exUploadPost" method="post" enctype="multipart/form-data">
		<div>
			<input type="file" name="files">
		</div>
		
		<div>
			<input type="file" name="files">
		</div>
		
		<div>
			<input type="file" name="files">
		</div>
		
		<div>
			<input type="file" name="files">
		</div>
		
		<div>
			<input type="file" name="files">
		</div>
		<div>
			<input type="submit">
		</div>
	</form>
</body>
</html>

 

파일을 하나만 올린 후 전송을 누른 결과이다.