2018. 4. 3. 21:41
반응형

스프링에서 파일을 업로드해서 저장할 필요가 있다.

그리고 csv나 txt파일 등을 업로드하고 파일의 내용을 자바에서 처리해야할 필요도 있을 때가 있다.

 

간단한 파일 업로드 예제를 통해 방법을 알아봤다.

우선 pom.xml에 다음을 추가한다.

 

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

 

그리고 servlet-context.xml에 다음을 추가한다.

업로드 최대 용량을 결정할 수 있다.

 

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
	<beans:property name="maxUploadSize" value="20971520">
	</beans:property> 
</beans:bean>

 

jsp파일에 다음과 같이 폼을 작성한다.

ajax를 통한 전송을 할 것이므로 jQuery를 추가해야한다.

 

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="testForm" enctype="multipart/form-data">
	<input type="text" id="name"/>
	<input type="file" id="file"/>
	<button id="button">submit</button>
</form>
<script>
	$(document).ready(function(){
		$("#button").click(function(event){
			event.preventDefault();
			var form = $("#testForm");
			var formData = new FormData(form);
			formData.append("file", $("#file")[0].files[0]);
			$.ajax({
				url: 'test',
				processData: false,
				contentType: false,
				data: formData,
				type: 'POST',
				success: function(data){
					console.log(data);
				}
			});
		});
	});
</script>

 

컨트롤러에는 다음과 같이 매핑한다.

파일을 업로드하면 파일의 이름, 파일형식을 출력시킬 수 있다.

그리고 try 안의 BufferedReader 등을 활용해 파일의 내용을 출력할 수 있다.

그 아래의 transferTo 메소드는 파일이 서버의 realPath에 업로드되도록 한다.

 

@RequestMapping(value="/test", method=RequestMethod.POST)
public @ResponseBody int test(MultipartHttpServletRequest request) {
	MultipartFile file = request.getFile("file1");
	String name = request.getParameter("name");
	System.out.println(name);
	System.out.println(file.getName());
	System.out.println(file.getOriginalFilename());
	System.out.println(file.getContentType());
	
	String realPath = request.getSession().getServletContext().getRealPath("/resources/upload/");
	System.out.println(realPath);
	File dir = new File(realPath);
	if(!dir.exists()) dir.mkdirs();
	try {
		String line;
		BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"));
		while((line=br.readLine()) != null) {
			System.out.println(line);
		}
		br.close();
		
		file.transferTo(new File(realPath, file.getOriginalFilename()));
	}catch (Exception e) {
		e.printStackTrace();
	}
	return 1;
}

 

 

Spring Framework file upload complete

반응형