온 코딩

[Spring](게시판 예제) 파일 업로드 기능 본문

복습 ARCHIVE/모델별 프로젝트

[Spring](게시판 예제) 파일 업로드 기능

SummerON 2021. 6. 28. 16:22

1.  JSP 수정

  • form enctype="multipart/form-data" 설정 
  • 파일 업로드 칸 추가
  • <input type="file" name="uploadFile">
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 상세</title>
</head>

<body align="center">
	<h1>글 등록</h1>
	<h3><a href="logout_proc.jsp">Log-out</a></h3>
	<hr>
	
	<div align="center">
	<form action="insertBoard.do" method="post" enctype="multipart/form-data">
		<table border="1" cellpadding="0"  cellspacing="0">
			<tr>
				<td bgcolor="orange" width="70">제목</td>
				<td align="left"><input type="text" name="title" required="required"></td>
			</tr>
			<tr>
				<td bgcolor="orange" width="70">작성자</td>
				<td align="left"><input type="text" name="writer" required="required"></td>
			</tr>
			<tr>
				<td bgcolor="orange" width="70">내용</td>
				<td align="left"><textarea name="content" cols="40" rows="10"></textarea></td>
			</tr>
			<tr>
				<td bgcolor="orange" width="70">업로드</td>
				<td align="left"><input type="file" name="uploadFile"></td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="새글 등록" />
				</td>
			</tr>
		</table>
	</form>
	</div>
			
	<hr>
	<a href="getBoardList.do">글 목록 가기</a>			
</body>
</html>

 

2. BoardVO / command 객체 설정 추가

private MultipartFile uploadFile  추가

 

3. 라이브러리 추가 (pom.xml)

  • 파일업로드 디팬던시 추가 -> 메이븐 확인하기
			<!-- FileUpload -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>

 

4. 스프링설정파일(presentation-layer.xml) 추가

MultipartResolver 설정 

클래스 객체 이름은 무조건 "multipartResolver"여야 함 (대부분 Resolver으로 끝나는 클래스들은 아이디가 정해져있음)

DispatcherServlet에서 지정한 이름임 

<!-- 파일업로드 설정 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<property name="maxUploadSize" value="100000"></property>
    </bean>

* 파일크기를 따로 설정하지 않으면 기본값 "-1"(무제한) 설정됨으로 보통은 꼭 최대크기를 설정함 

VO의 멀티파트 변수 객체 생성 시, 스프링컨테이너에 의해 multipartResolver라는 이름으로 등록된 CommonMultipartResolver 객체 생성 

 

MultipartFile 메서드 

메서드 설명
String getOriginalFilename() 업로드한 파일 명을 문자열로 리턴
void transfer(File destFile) 업로드한 파일을 destFile에 저장
boolean isEmpty() 업로드한 파일 존재 여부 리턴(없으면 true)

 

5. 파일 업로드 컨트롤러 

@RequestMapping(value = "/insertBoard.do")
	public String insertBoard(BoardVO vo) throws IOException {
		System.out.println("어노테이션 컨트롤러 : 글 등록 처리");
		// 파일 업로드 처리
		MultipartFile uploadFile = vo.getUploadFile();
		if (!uploadFile.isEmpty()) {
			String fileName = uploadFile.getOriginalFilename();
			uploadFile.transferTo(new File("C:/work/" + fileName));
		}

		boardService.insertBoard(vo);
		return "redirect:getBoardList.do";
	}// POJO 스타일
Comments