업로드
testMapper.xml
((((디비 테이블에file_name varchar(40)넣기))))
<!--게시글 삽입 -->
<insert id="insertTest" parameterType="TestVO">
<![CDATA[
INSERT INTO test(testTitle, testContent, testName, testDate, fileName)
VALUES(#{testTitle}, #{testContent}, '밥샵', now(), #{fileName})
]]>
</insert>
<!--게시글 클릭시 detailView -->
<select id="selectDetail"
parameterType="egovframework.example.test.domain.TestVO"
resultType="egovframework.example.test.domain.TestVO">
<![CDATA[
SELECT *
FROM test
WHERE testId = #{testId}
]]>
</select>
<!--게시글 업데이트 -->
<update id="updateTest">
update test set
testTitle = #{testTitle}
,testContent = #{testContent}
,fileName = #{fileName}
where
testId = #{testId}
</update>
pom.xml
<!-- 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>
dispatcher-servlet.xml
<!-- 파일 업로드 설정 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 파일 사이즈 설정 가능 byte 단위
<property name="maxUploadSize" value="100000" />
-->
</bean>
testRegister.jsp
<tr>
<th>첨부파일:</th>
<td><input type="file" name="uploadFile"></td>
</tr>
TestController
package egovframework.example.test.web;
import java.io.File;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import egovframework.example.test.domain.Search;
import egovframework.example.test.domain.TestVO;
import egovframework.example.test.service.TestService;
@Controller
public class TestController {
@Autowired
private TestService testServiceImpl;
// 글 목록 리스트, 페이징, 검색
@RequestMapping(value = "/testList.do")
public String testListDo(Model model, @RequestParam(required = false, defaultValue = "1") int page,
@RequestParam(required = false, defaultValue = "1") int range,
@RequestParam(required = false, defaultValue = "testTitle") String searchType,
@RequestParam(required = false) String keyword, @ModelAttribute("search") Search search) throws Exception {
// 검색
model.addAttribute("search", search);
search.setSearchType(searchType);
search.setKeyword(keyword);
// 전체 게시글 개수를 얻어와 listCnt에 저장
int listCnt = testServiceImpl.getBoardListCnt(search);
// 검색
search.pageInfo(page, range, listCnt);
// 페이징
model.addAttribute("pagination", search);
// 게시글 화면 출력
model.addAttribute("list", testServiceImpl.selectTest(search));
return "test/testList";
}
// 글 작성 클릭시 글 작성 페이지로 이동
@RequestMapping(value = "/testRegister.do")
public String testRegister() {
return "test/testRegister";
}
// 글 작성 버튼 구현
@RequestMapping(value = "/insertTest.do")
public String write(@ModelAttribute("testVO") TestVO testVO, RedirectAttributes rttr) 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("C:\\upload\\" + fileName));
}
testVO.setFileName(fileName);
testServiceImpl.insertTest(testVO);
return "redirect:testList.do";
}
// HttpServletRequest 객체안에 모든 데이터들이 들어가는데 getParameter메소드로 testId 원하는 데이터 가져옴
// 제목 클릭 시 상세보기
@RequestMapping(value = "/testDetail.do")
public String viewForm(@ModelAttribute("testVO") TestVO testVO, Model model, HttpServletRequest request)
throws Exception {
int testId = Integer.parseInt(request.getParameter("testId"));
testVO.setTestId(testId);
TestVO resultVO = testServiceImpl.selectDetail(testVO);
model.addAttribute("result", resultVO);
return "test/testDetail";
}
// 수정하기
@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("C:\\upload\\" + fileName));
}
testVO.setFileName(fileName);
testServiceImpl.updateTest(testVO);
return "redirect:testList.do";
}
// 삭제하기
@RequestMapping(value = "/deleteTest.do")
public String deleteTest(@ModelAttribute("testVO") TestVO testVO) throws Exception {
testServiceImpl.deleteTest(testVO);
return "redirect:testList.do";
}
}
TestVO
private String fileName;
private MultipartFile uploadFile;
다운로드
FileDownController.java
package egovframework.example.test.web;
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;
@Controller
public class FileDownController {
@RequestMapping(value = "fileDownload.do")
public void fileDownload4(HttpServletRequest request,HttpServletResponse response) throws Exception {
//String path = request.getSession().getServletContext().getRealPath("저장경로");
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 ex) {
System.out.println("UnsupportedEncodingException");
}
realFilename = "C:\\upload\\" + filename;
System.out.println(realFilename);
File file1 = new File(realFilename);
if (!file1.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 ncount = 0;
byte[] bytes = new byte[512];
while ((ncount = fis.read(bytes)) != -1 ) {
os.write(bytes, 0, ncount);
}
fis.close();
os.close();
} catch (Exception e) {
System.out.println("FileNotFoundException : " + e);
}
}
}
testDetail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!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">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 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">
<!-- Latest compiled and minified JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
<link href="/css/test/test.css" rel="stylesheet" type="text/css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered">
<thead>
<h1>글 상세보기 Detail</h1>
</thead>
<tbody>
<form action="updateTest.do" id="viewForm" method="post"
encType="multipart/form-data">
<tr>
<th>글번호:</th>
<td><input name="testId" type="text" value="${result.testId}"
class="form-control" readonly /></td>
</tr>
<tr>
<th>제목:</th>
<td><input type="text" value="${result.testTitle}"
name="testTitle" class="form-control" /></td>
</tr>
<tr>
<th>내용:</th>
<td><textarea name="testContent" class="form-control"
style="height: 200px;">${result.testContent}</textarea></td>
</tr>
<tr>
<c:if test="${result.fileName ne null}">
<tr>
<td>다운로드</td>
<td><a href="fileDownload.do?fileName=${result.fileName}">
<input type="text" id="asd" value="${result.fileName}"
name="fileName" class="form-control" readonly />
</a>
<button id="asdasd" type="button" class="btn_previous">파일지우기</button>
</tr>
</c:if>
</tr>
<tr>
<th>첨부파일:</th>
<td><input type="file" name="uploadFile"></td>
</tr>
<tr>
<td colspan="2">
<button id="btn_previous" type="button" class="btn_previous">이전</button>
<button id="btn_delete" type="button" class="btn_previous">삭제</button>
<button id="btn_modify" type="button" class="btn_register">수정</button>
</tr>
</form>
</tbody>
</table>
</div>
</body>
<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) {
if (confirm("정말 삭제하시겠습니까 ?") == true) {
$("#viewForm").attr("action", "deleteTest.do");
$("#viewForm").submit();
} else {
return;
}
});
//이전 클릭 시 testList로 이동
$("#btn_previous").click(function javascript_onclikc() {
$(location).attr('href', 'testList.do');
});
$("#asdasd").click(function javascript_onclikc() {
$('#asd').val(null);
});
</script>
</html>
파일 업로드와 파일 다운로드, 파일 삭제를 구현하였다.
참고블로그
extsdd.tistory.com/category/IT/Spring(spring의 좋은 설명)
gangnam-americano.tistory.com/3
ming9mon.tistory.com/65?category=825118
haenny.tistory.com/67(egov 게시판 sample예제 삭제)
badstorage.tistory.com/13(게시글 목록 갯수 변경)
lemontia.tistory.com/408?category=993095 (mapper namespace)
'Spring Framework > 게시판 연습' 카테고리의 다른 글
7. ajax게시판 만들기(작성, 수정, 삭제)(JSON형태로 AJAX비동기 통신) (0) | 2020.10.20 |
---|---|
6. ajax게시판 만들기(list,페이징,검색,selectbox)(JSON형태로 AJAX비동기 통신) (0) | 2020.10.19 |
4. 게시판 만들기 (페이징, 검색, 페이지 목록 갯수 변경하기) (0) | 2020.09.25 |
3. 게시판 만들기 CRUD 게시물 작성 수정 삭제 (2) | 2020.09.24 |
2. 게시판 만들기 maria DB 연결 (0) | 2020.09.22 |