티스토리 뷰

[JAVA]/Spring

[Spring] 파일 업로드

춘햄 2021. 6. 28. 12:03

일반적인 Dynamic Web 프로젝트에서 한번 파일 업로드/다운로드를 다룬 적이 있다. Spring 환경에서도 마찬가지로 이 기능들을 구현할 수 있는데, 다른 점은 apache 에서 제공하는 Common FileUpload 라이브러리를 사용하며, pom.xml 파일과 스프링 설정 파일을 조금 수정해줘야 한다는 점이다.

 

바로 들어가보자.


우선 View 에서 파일을 서버로 보낼 수 있게끔 수정해준다. 

 

◎insertBoard.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>

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

<body align="center">
  <h1>글 등록</h1>
  <h3><a href="logout.do">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>

 

File 타입이 하나 더 생성되었으므로, VO 파일(Command 객체) 도 다음과 같이 수정한다.

 

◎BoardVO.java

public class BoardVO {

	private int seq;
	private String title;
	private String writer;
	private String content;
	private Date regDate;
	private int cnt;
	private MultipartFile uploadFile;
	
	public MultipartFile getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(MultipartFile uploadFile) {
		this.uploadFile = uploadFile;
	}

...

 

이후에 Apache에서 제공하는 Common FileUpload 라이브러리를 사용하기 위해 pom.xml 에서 dependency를 추가해준다.

 

◎pom.xml

<!--  FileUpload -->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>
		

 

라이브러리 추가를 확인했다면, 다음은 스프링 설정 파일에서 CommonsMultipartResolver를 bean 객체로 등록해야 한다.

 

◎presentation-layer.xml

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

	<!-- component scan Registration : Controller's -->
	<context:component-scan base-package="com.freeflux.view"></context:component-scan>

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

</beans>

 

 마지막으로 Controller에 insertBoard.do 요청에 따른 메서드를 수정하면 끝이 난다.

 

◎Controller

@RequestMapping(value="/insertBoard.do")
public String insertBoard(BoardVO vo, BoardDAO boardDAO) throws IOException {
  System.out.println("글 등록 처리");
  //파일 업로드 처리
  MultipartFile uploadFile = vo.getUploadFile();
  if(!uploadFile.isEmpty()) {
    String fileName = uploadFile.getOriginalFilename();
    uploadFile.transferTo(new File("C:/" + fileName));
  }
  boardService.insertBoard(vo);
  return "getBoardList.do";
}

 

Comments