우리가 수정할 파일은 다음과 같다.

아래와 같이 표시하였으니 참고하도록 하자

파일 업로드의 코드 작업 순서는 다음과 같다.

1. view의 jsp 파일에서 form에 enctype 추가 및 input file type 설정
2. servlet-context.xml에서 multipartResolver bean 추가
3. BoardVO에 MultipartFile type 변수와 fileName을 저장할 String 변수 선언
4. BoardControllerImpl에서 파일 업로드를 가능하도록 코드 수정

그럼 다음과 같이 순서대로 보도록하자

1. view의 jsp 파일에서 form에 enctype 추가 및 input file type 설정

아래와 같이 주석으로 수정된 부분을 표시하였다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
	$(document).ready(function() {
		$("#btnStr").click(function() {
			window.open("/board/insertPW.do", "", "width=500, height=300");
		});
	})
</script>
</head>
<body>
	<div align="center">
	<!-- 파일 다운을 위하여 enctype 설정 -->
		<form name="f1" method="post" enctype="multipart/form-data" action="/board/insertBoard.do">
			<input type="hidden" name="writer" value="${sessionNAME}" />
			<table border=1>
				<tr>
					<td>제목</td>
					<td width="600px"><input type="text" name="subject" style="width:590px"></td>
				</tr>
				<tr>
					<td>내용</td>
					<td width="300px" height="300px"><textarea
							style="width: 98%; height: 500px" name="content"></textarea></td>
				</tr>
				<tr>
				<!-- type을 file을 설정 및 name을 vo에 등록된 이름과 동일하게 설정 -->
				<td colspan="2"><input type="file" name="uploadFile"/></td>
				</tr>
				<tr align="center">
					<td colspan="2"><input type="button" id="btnStr"
						value="비밀번호 설정"> <c:if test="${passwd == null }">N</c:if>
						<c:if test="${passwd != null }">Y
				<input type="hidden" name="passwd" value="${passwd }" />
						</c:if></td>
				</tr>
				<tr>
					<td colspan="2" align="center"><input type="submit" value="저장"> <input
						type="button" value="취소"
						onclick="location.href='/board/listBoard.do'"></td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

2. servlet-context.xml에서 multipartResolver bean 추가

그리고 아래 주석으로 표시한 것과 같이 bean 처리하였다.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<interceptors>
		<interceptor>
			<mapping path="/*/*.do"/>
			<beans:bean class="com.nuri.common.interceptor.ViewNameInterceptor"></beans:bean>
		</interceptor>
	</interceptors>
	
	<context:component-scan base-package="com.nuri" />
	
	<!-- 다음과 같이 multipartResolver를 bean처리 해줘야 다운로드가 가능하다. -->
	<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<beans:property name="maxUploadSize" value="10485760"></beans:property>
	</beans:bean>
	
</beans:beans>

3. BoardVO에 MultipartFile type 변수와 fileName을 저장할 String 변수 선언

VO에는 다음과 같이 변수를 추가하였다.

4. BoardControllerImpl에서 파일 업로드를 가능하도록 코드 수정하였다.

	@Override
	@RequestMapping(value="/board/insertBoard.do")
	public String insertBoard(BoardVO vo, HttpServletRequest request) throws IllegalStateException, IOException {
		System.out.println("===>Controller로 insertBoard 접속");
		//MultipartFile로 파일 정보를 받음
		MultipartFile uploadFile = vo.getUploadFile();
		System.out.println("uploadFile : "+uploadFile);
		//randomUUID로 랜덤값 받음
		String genId = UUID.randomUUID().toString().substring(5, 12);
		// realPath로 프로젝트에 fileSave 폴더에 값을 저장함
		String realPath = request.getSession().getServletContext().getRealPath("/fileSave/");
		System.out.println("경로 : "+realPath);
		
		// 만약 uploadFile이 비어있지않다면 다음과 같이 코드 실행
		if(!uploadFile.isEmpty()) {
			System.out.println("여기 접속?");
			// originalFileName에 원본 파일명을 저장한다.
			String originalFileName = uploadFile.getOriginalFilename();
			System.out.println("originalFileName : "+originalFileName);
			// saveFileName에 랜덤값이 저장된 genID와 파일명을 저장한다.
			String saveFileName = genId + "." + FilenameUtils.getExtension(originalFileName);
			System.out.println("saveFileName : "+saveFileName);
			// 아래 함수로 파일을 업로드한다.
            uploadFile.transferTo(new File(realPath+saveFileName));
			// 다음 함수로 파일명을 vo에 저장한다.
            vo.setFileName(saveFileName);
		}
		
		boardService.insertBoard(vo);
		return "redirect:/board/listBoard.do";
	}

그럼 다음과 같이 파일 업로드를 진행해보자.

다음과 같이 경로와 originalFileName 그리고 saveFileName을 확인할 수 있다.

각 메소드는 필자의 블로그 명령어 카테고리에서 확인하도록하자.

+ Recent posts