-
전자정부프레임워크기반 게시판 만들기 (6) 파일 업로드,다운로드DEV/Spring 2020. 12. 31. 12:09
pom.xml
12345678910111213<!-- file upload --><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><!-- MultipartHttpServletRequset --><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.6</version></dependency>cs 추가후 Maven Update 꼭!!해주기
dispatcher-servlet.xml
12345<!-- 파일 업로드 설정 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="maxUploadSize" value="100000000" /><property name="maxInMemorySize" value="100000000" /></bean>cs testMapper.xml
1234567891011121314<!-- 게시글 삽입 --><insert id="insertTest" parameterType="egovframework.example.ivory.vo.TestVo"><![CDATA[INSERT INTO test(testTitle, testContent, testName, testDate, fileName)VALUES(#{testTitle},#{testContent},'ivory',now(),#{fileName})]]></insert><!-- 게시글 수정 --><update id="updateTest" parameterType="egovframework.example.ivory.vo.TestVo">UPDATE test SETtestTitle = #{testTitle}, testContent = #{testContent}, fileName = #{fileName}WHERE testId = #{testId}</update>cs 삽입,수정부분만 fileName 추가
TestVo에 필드추가
12private String fileName;private MultipartFile uploadFile;cs +getter, setter
testRegister.jsp
123456789101112131415161718192021222324<form id="form_test" action="insertTest.do" method="post" encType="multipart/form-data"><table class="table table-bordered"><tbody><tr><th>제목</th><td><input type="text" placeholder="제목을 입력하세요." name="testTitle" class="form-control" /></td></tr><tr><th>내용</th><td><textarea placeholder="내용을 입력하세요 ." name="testContent" class="form-control" style="height: 200px;"></textarea></td></tr><tr><th>첨부파일</th><td><input type="file" name="uploadFile"></td></tr><tr><td colspan="2"><button id="btn_register" type="button" class="btn_register">등록</button><button id="btn_previous" type="button" class="btn_previous">이전</button></tr></tbody></table></form>cs form에 encType="multipart/form-data" 추가, 첨부파일 input 추가
TestController.java
123456789101112131415161718192021222324252627282930313233343536373839404142434445// 글쓰기@RequestMapping(value = "/insertTest.do")public String write(@ModelAttribute("testVo") TestVo testVo) throws Exception {// 파일 업로드 처리String fileName = null;MultipartFile uploadFile = testVo.getUploadFile();if (!uploadFile.isEmpty()) {String originalFileName = uploadFile.getOriginalFilename();String ext = FilenameUtils.getExtension(originalFileName); // 확장자 구하기UUID uuid = UUID.randomUUID(); // UUID 구하기fileName = uuid + "." + ext;uploadFile.transferTo(new File("D:\\upload\\" + fileName));}testVo.setFileName(fileName);System.out.println(testVo.getFileName());testService.insertTest(testVo);return "redirect:testList.do";}// 글수정@RequestMapping(value = "/updateTest.do")public String updateTest(@ModelAttribute("testVo") TestVo testVo, HttpServletRequest request) throws Exception {// 파일 업로드String fileName = null;MultipartFile uploadFile = testVo.getUploadFile();if (!uploadFile.isEmpty()) {String originalFileName = uploadFile.getOriginalFilename();String ext = FilenameUtils.getExtension(originalFileName); // 확장자구하기UUID uuid = UUID.randomUUID(); // uuid구하기fileName = uuid + "." + ext;uploadFile.transferTo(new File("D:\\upload\\" + fileName));testVo.setFileName(fileName);}else{testService.updateTest(testVo);return "redirect:testDetail.do?testId=" + testVo.getTestId();}testService.updateTest(testVo);return "redirect:testDetail.do?testId=" + testVo.getTestId();}cs 파일 업로드 완료
FileDownloadController클래스 생성
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374package egovframework.example.ivory.controller;import java.io.File;import java.io.FileInputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class FileDownloadController {@RequestMapping(value = "fileDownload.do")public void fileDownload(HttpServletRequest request, HttpServletResponse response) throws Exception {String filename = request.getParameter("fileName");String realFilename = "";System.out.println(filename);try {String browser = request.getHeader("User-Agent");// 파일 인코딩if (browser.contains("MSIE") || browser.contains("Trident") || browser.contains("Chrome")) {filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");} else {filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");}} catch (UnsupportedEncodingException e) {System.out.println("UnsupportedEncodingException 발생");}realFilename = "D:\\upload\\" + filename;System.out.println(realFilename);File file = new File(realFilename);if (!file.exists()) {return;}// 파일명 지정response.setContentType("application/octer-stream");response.setHeader("Content-Transfer-Encoding", "binary");response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");try {OutputStream os = response.getOutputStream();FileInputStream fis = new FileInputStream(realFilename);int cnt = 0;byte[] bytes = new byte[512];while ((cnt = fis.read(bytes)) != -1) {os.write(bytes, 0, cnt);}fis.close();os.close();} catch (Exception e) {e.printStackTrace();}}}cs testDetail.jsp
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106<%@ 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 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>Board Detail</title><!-- Latest compiled and minified CSS --><link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"crossorigin="anonymous"><!-- Optional theme --><link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"crossorigin="anonymous"></head><body><br /><h1 class="text-center">Board Detail</h1><br /><br /><div class="container"><form action="updateTest.do" id="viewForm" method="post" encType="multipart/form-data"><table class="table table-bordered"><tbody><tr><th>글번호</th><td><input name="testId" type="text" value="${vo.testId}" class="form-control" readonly /></td></tr><tr><th>제목</th><td><input type="text" value="${vo.testTitle}" name="testTitle" class="form-control" /></td></tr><tr><th>내용</th><td><textarea name="testContent" class="form-control" style="height: 200px;">${vo.testContent}</textarea></td></tr><tr><c:if test="${vo.fileName ne null}"><tr><th>다운로드</th><td><a href="fileDownload.do?fileName=${vo.fileName}"><input type="text" id="filename" value="${vo.fileName}" name="fileName" class="form-control" readonly="readonly" /></a><button id="filedelete" type="button" class="btn_previous" style="float: right">파일삭제</button></tr></c:if></tr><tr><th>첨부파일</th><td><input type="file" name="uploadFile"></td></tr><tr><td colspan="2" style="text-align: right;"><button id="btn_previous" type="button" class="btn_previous">이전</button><button id="btn_modify" type="button" class="btn_register">수정</button><button id="btn_delete" type="button" class="btn_delete">삭제</button></td></tr></tbody></table></form></div><!-- Latest compiled and minified JavaScript --><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"crossorigin="anonymous"></script><script src="https://code.jquery.com/jquery-1.12.4.js"></script><script type="text/javascript">$(document).on('click', '#btn_modify', function(e) {if (confirm("정말 수정하시겠습니까 ?") == true) {$("#viewForm").submit();} else {return;}});$(document).on('click', '#btn_delete', function(e) {var testId = ${vo.testId};if (confirm("정말 삭제하시겠습니까 ?") == true) {$("#viewForm").attr("action", "deleteTest.do?testId="+testId);$("#viewForm").submit();} else {return;}});//이전 클릭 시 testList로 이동$("#btn_previous").click(function previous() {$(location).attr('href', 'testList.do');});$("#filedelete").click(function deletefile() {$('#filename').val(null);});</script></body></html>cs 마찬가지로 form에 encType="multipart/form-data" 추가,
다운로드, 첨부파일 항목을 추가해주고 파일삭제버튼을 눌렀을때 작동할 script문을 추가해준다.
파일 다운로드 완료
'DEV > Spring' 카테고리의 다른 글
[Spring] 스프링 프레임워크 특징/ POJO / IoC / DI / AOP / PSA (0) 2024.05.08 [Spring] Jasypt 프로퍼티스 암호화 (0) 2022.09.20 전자정부프레임워크기반 게시판 만들기 (5) 페이징,검색 (2) 2020.12.30 전자정부프레임워크기반 게시판 만들기 (4) 글 상세보기,삽입,수정,삭제 (2) 2020.12.30 전자정부프레임워크기반 게시판 만들기 (3) MariaDB연동, 게시판 리스트 출력 (18) 2020.12.29