Dev/Spring

Spring2.5 - 파일게시판(업로드/다운로드/삭제)

창문닦이 2019. 4. 8. 18:45

파일전송을 위한 multipartResolver 설정 (dispatcher-servlet.xml)

스프링이 제공하는 파일 업로드 처리 기능을 사용하려면 먼저 MultipartResolver 를 빈으로 등록해야한다. 
스프링은 Apache Commons FileUpload API를 이용하여 파일 업로드를 처리하는 CommonsMultipartResolver 클래스를 제공한다.

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<property name="defaultEncoding" value="UTF-8"/>

<property name="maxUploadSize" value="10000000"/>

</bean>


CommonsMultipartResolver의 주요 프로퍼티

 프로퍼티

  설명

 defaultEncoding

 기본 인코딩 설정. 필터를 통해 인코딩을 설정한 경우 해당 인코딩을 사용한다.(기본 값 : ISO-8859-1)

 maxUploadSize

 업로드할 최대 크기를 지정 한다. -1인 경우 제한을 두지 않는다.(기본 값 : -1)

 maxInMemorySize

 업로드한 내용을 메모리에 저장할 최대 크기를 지정 한다. 최대 크기를 넘으면 임시 디렉토리에 저장.(기본 값 : 1024)

 uploadTempDir

 업로드한 파일이 저장할 임시 디렉토리 경우(기본 값 : 서블릿 컨테이너 임시 디렉토리)

1. 테이블 생성

CREATE TABLE FILETEST

(NUM NUMBER(7) PRIMARY KEY,

SUBJECT VARCHAR2(50) NOT NULL,

SAVEFILENAME VARCHAR2(50),

ORIGINALFILENAME VARCHAR2(50))

2-1. iBatis 셋팅 - sqlMapConfig.xml 에 resource 등록

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"

"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>

<settings

cacheModelsEnabled="false"

useStatementNamespaces="true"/>

<sqlMap resource="com/util/sqlMap/temp_sqlMap.xml"/>

<sqlMap resource="com/util/sqlMap/bbs_sqlMap.xml"/>

<sqlMap resource="com/util/sqlMap/file_sqlMap.xml"/>

</sqlMapConfig>

2-2. iBatis 셋팅 - sql문 작성

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sqlMap

PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="fileTest">

<select id="numMax" resultClass="int">

select nvl(max(num),0) from fileTest

</select>

<!-- 업로드 파일 데이터 DB 등록 -->

<insert id="insertData" parameterClass="com.fileTest.FileCommand">

insert into fileTest (num,subject,saveFileName,originalFileName)

values (#num#,#subject#,#saveFileName#,#originalFileName#)

</insert>

<!-- 업로드 파일 갯수 카운팅 -->

<select id="dataCount" resultClass="int" >

select nvl(count(*),0) from fileTest

</select>

<!-- 페이징 작업을 위해 where조건 반영 -->

<select id="listData" resultClass="com.fileTest.FileCommand" parameterClass="map">

<![CDATA[

select * from(

select rownum rnum, data.* from(

select num,subject,saveFileName,originalFileName

from fileTest order by num desc) data)

where rnum>=#start# and rnum<=#end#

]]>

</select>

<!-- 다운로드시 -->

<select id="readData" resultClass="com.fileTest.FileCommand" parameterClass="int">

select num,subject,saveFileName,originalFileName

from fileTest where num=#num#

</select>

<!-- 삭제 -->

<delete id="deleteData" parameterClass="int">

delete fileTest where num=#num#

</delete>

</sqlMap>

3-1. JSP페이지 - 업로드페이지(View)

enctype="multipart/form-data"
파일을 업로드 하기 위해서는 <form> 태그의 enctype 속성의 값을 "multipart/form-data"로 지정해야 한다.

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

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>업로드</title>

</head>

<body>

<form action="<%=cp%>/file/created.action" method="post" enctype="multipart/form-data" name="myForm" >

<table cellpadding="2" id="bbs">

<tr>

<td id="bbs_title" colspan="3">

파일 등록

</td>

</tr>

<tr><td height="1" colspan="3" style="border-bottom:1px solid #DBDBDB;"></td></tr>

<tr><td height="1" colspan="3" style="border-bottom:1px solid #DBDBDB;"></td></tr>

<tr>

<td align="center" width="100">제&nbsp;&nbsp;&nbsp;&nbsp;목</td>

<td colspan="2" >

<input type="text" name="subject" class="boxTF" size="74"/></td>

</tr>

<tr><td height="1" colspan="3" style="border-bottom:1px solid #DBDBDB;"></td></tr>

<tr>

<td align="center">파&nbsp;&nbsp;&nbsp;&nbsp;일</td>

<td class="bbsCreated_bottomLine" colspan="2" >

<input type="file" name="upload" class="boxTF" size="74"/></td>

</tr>

<tr><td height="1" colspan="3" style="border-bottom:1px solid #DBDBDB;"></td></tr>

<tr id="bbsCreated_footer">

<td colspan="3" align="center">

<input type="hidden" name="mode" value="save">

<input type="submit" value="파일등록"/>

<input type="button" value="다시입력" onclick="document.myForm.subject.focus();"/>

<input type="button" value="작성취소" onclick="javascript:location.href='<%=cp %>/file/list.action';"/>

</td>

</tr>

</table>

</form>

</body>

</html>

3-2. JSP페이지 - 리스트페이지(View)

<%@page import="java.net.URLDecoder"%>

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

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>파일 리스트</title>

</head>

<body>

<br/><br/>

<table width="500" align="center">

<tr height="30">

<td align="right">

<input type="button" value="파일올리기"

onclick="javascript:location.href='<%=cp%>/file/created.action';"/>

</td>

</tr>

</table>

<table width="500" align="center" border="1" style="font-size: 10pt;">

<tr height="30" align="center">

<td width="50">번호</td>

<td width="200">제목</td>

<td width="200">파일</td>

<td width="50">삭제</td>

</tr>

<c:forEach var="dto" items="${lists}">

<tr height="30" onmouseover="this.style.backgroundColor='#e4e4e4'"

onmouseout="this.style.backgroundColor=''" bgcolor="#ffffff">

<td width="50" align="center">${dto.listNum}</td>

<td width="200" align="left">${dto.subject}</td>

<td width="200" align="left">

<a href="${dto.urlFile }">${dto.originalFileName}</a>

</td>

<td width="50" align="center">

<a href="<%=cp%>/file/delete.action?num=${dto.num}">삭제</a>

</td>

</tr>

</c:forEach>

<c:if test="${totalDataCount==0 }">

<tr bgcolor="#ffffff">

<td align="center" colspan="4">등록된 자료가 없습니다.</td>

</tr>

</c:if>

</table>

<c:if test="${totalDataCount!=0 }">

<table width="600" border="0" cellpadding="3" cellspacing="0" align="center">

<tr align="center">

<td align="center" height="30">${pageIndexList}</td>

</tr>

</table>

</c:if>

</body>

</html>

4. command 클래스 

MultipartFile 인터페이스는 업로드한 파일과 관련된 정보를 구할 수 있는 메소드를 제공한다.

package com.fileTest;

import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;

public class FileCommand {

private int num;

private int listNum;

private String subject;

private String saveFileName;

private String originalFileName;

private String urlFile;

private InputStream inputStream;

private MultipartFile upload; // file 태그 name 속성 일치해야 함

getter,setter 작성

}

5. FileController 클래스

package com.fileTest;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.io.PrintWriter;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.multipart.MultipartFile;

import com.util.FileManager;

import com.util.MyUtil;

import com.util.dao.CommonDAO;


@Controller("fileTest.fileController")

public class FileController {

//객체 생성

@Resource(name="dao")

private CommonDAO dao;

@Resource(name="myUtil")

private MyUtil myUtil;

@Resource(name="fileManager")

private FileManager fileManager;

@RequestMapping(value="/file/created.action",method={RequestMethod.GET,RequestMethod.POST})

public String created(String mode, FileCommand command,HttpServletRequest request,

HttpSession session) throws Exception{

//올린 파일정보가 없을 경우 /fileTest/write.jsp 페이지로 이동

if(command.getUpload()==null){

request.setAttribute("mode", "insert");

return "fileTest/write";

}

MultipartFile file = command.getUpload();

InputStream is = file.getInputStream();

String root = session.getServletContext().getRealPath("/");

String savePath = root + File.separator + "pds" + File.separator + "data";

String originalFileName = command.getUpload().getOriginalFilename();

String newFileName = FileManager.doFileUpload(is,originalFileName,savePath);

int numMax = dao.getIntValue("fileTest.numMax");

command.setNum(numMax + 1);

command.setOriginalFileName(originalFileName);

command.setSaveFileName(newFileName);

dao.insertData("fileTest.insertData", command);

return "redirect:/file/list.action";//스프링의 리다이렉트

}

@RequestMapping(value="/file/list.action",method={RequestMethod.GET,RequestMethod.POST})

public String list(HttpServletRequest request, HttpSession session) throws Exception{

int numPerPage = 5;

int totalPage = 0;

int totalDataCount = 0;

String pageNum = request.getParameter("pageNum");

String cp = request.getContextPath();

int currentPage = 1;

if(pageNum!=null&&!pageNum.equals("")){

currentPage = Integer.parseInt(pageNum);

}

totalDataCount = dao.getIntValue("fileTest.dataCount");

if(totalDataCount!=0)

totalPage = myUtil.getPageCount(numPerPage, totalDataCount);

if(currentPage>totalPage)

currentPage = totalPage;

Map<String, Object> hMap = new HashMap<String,Object>();

int start = (currentPage-1)*numPerPage+1;

int end = currentPage*numPerPage;

hMap.put("start", start);

hMap.put("end", end);

List<Object> lists = (List<Object>)dao.getListData("fileTest.listData",hMap);

//번호 재정렬 작업

Iterator<Object> it = lists.iterator();

int listNum,n=0;

String str;

while(it.hasNext()){

//전체 데이터 갯수 6개일 때

//리스트번호가 10 8 6 (start=1)/ 5 4 3(start=4) 라 가정

// 1 2 3 / 4 5 6

FileCommand dto = (FileCommand)it.next();

listNum = totalDataCount - (start + n - 1) ;

dto.setListNum(listNum);

n++;

//파일 다운로드 경로

str = cp + "/file/download.action?num="+dto.getNum();

dto.setUrlFile(str);

}

String urlList = cp + "/file/list.action";

request.setAttribute("lists", lists);

request.setAttribute("pageNum", pageNum);

request.setAttribute("totalPage", totalPage);

request.setAttribute("totalDataCount", totalDataCount);

request.setAttribute("pageIndexList", myUtil.pageIndexList(currentPage, totalPage, urlList));

return "fileTest/list";

}

@RequestMapping(value="/file/delete.action",method={RequestMethod.GET,RequestMethod.POST})

public String delete(FileCommand command,HttpServletRequest request, HttpSession session) throws Exception{

String root = session.getServletContext().getRealPath("/");

String savePath = root + File.separator + "pds" +  File.separator + "data";

int num = Integer.parseInt(request.getParameter("num"));

//삭제해야하는 데이터 값 읽어오기

FileCommand dto = (FileCommand)dao.getReadData("fileTest.readData", num);

String saveFileName = dto.getSaveFileName();

FileManager.doFileDelete(saveFileName, savePath);

//DB삭제

dao.deleteData("fileTest.deleteData",num);

return "redirect:/file/list.action";

}

@RequestMapping(value="/file/download.action",method={RequestMethod.GET,RequestMethod.POST})

public String download(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception{

String root = session.getServletContext().getRealPath("/");

String savePath = root + File.separator + "pds" +  File.separator + "data";

int num = Integer.parseInt(request.getParameter("num"));

//다운로드 받을 데이터값 읽어오기

FileCommand dto = (FileCommand)dao.getReadData("fileTest.readData", num);

if(dto==null){

return "redirect:/file/list.action";

}

//다운로드 진행

boolean flag = FileManager.doFileDownload(dto.getSaveFileName(),dto.getOriginalFileName(), savePath, response);

if(!flag){

//다운로드 받지 못했을 시 실행

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

out.print("<script type='text/javascript'>");

out.print("alert('다운로드 에러!!!');");

out.print("history.back();");

out.print("</script>");

}

return null;

}

}

 6. 실행 페이지


'Dev > Spring' 카테고리의 다른 글

Spring 3.0 셋팅  (0) 2019.04.15
Spring2.5 - tiles  (0) 2019.04.09
Spring2.5 - 게시판 만들기  (0) 2019.04.08
Spring2.5 - Annotation  (0) 2019.04.08
Spring2.5 MVC - MultiActionController  (0) 2019.04.05