sql>tbl_board 테이블 생성
BoardVO
package com.example.domain;
import java.util.Arrays;
import java.util.Date;
public class BoardVO {
private int bno;
private String title;
private String content;
private Date regdate;
private String[] files;
public String[] getFiles() {
return files;
}
public void setFiles(String[] files) {
this.files = files;
}
public int getBno() {
return bno;
}
public void setBno(int bno) {
this.bno = bno;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getRegdate() {
return regdate;
}
public void setRegdate(Date regdate) {
this.regdate = regdate;
}
@Override
public String toString() {
return "BoardVO [bno=" + bno + ", title=" + title + ", content=" + content + ", regdate=" + regdate
+ ", files=" + Arrays.toString(files) + "]";
}
}
BoardDAO
package com.example.persistence;
import java.util.List;
import com.example.domain.BoardVO;
public interface BoardDAO {
public List<BoardVO> list();
public void insert(BoardVO vo);
public void addAttach(String filename);
public BoardVO read(int bno);
public List<String> getAttach(int bno);
public void update(BoardVO vo);
public void replaceAttach(int bno,String fileName);
public void deleteAttach(int bno);
public void delete(int bno);
}
BoardMapper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="BoardMapper">
<select id="list" resultType="com.example.domain.BoardVO">
select * from tbl_board
order by bno desc
limit 0,5
</select>
<insert id="insert">
insert into tbl_board(title,content)
values(#{title},#{content})
</insert>
<insert id="addAttach">
insert into tbl_attach(bno,filename)
values(last_insert_id(),#{filename})
</insert>
<select id="read" resultType="com.example.domain.BoardVO">
select * from tbl_board
where bno=#{bno}
</select>
<select id="getAttach" resultType="string">
select filename from tbl_attach
where bno=#{bno}
</select>
<update id="update">
update tbl_board set title=#{title},content=#{content}
where bno=#{bno}
</update>
<insert id="replaceAttach">
insert into tbl_attach(bno,fileName)
values(#{bno},#{fileName})
</insert>
<delete id="deleteAttach">
delete from tbl_attach
where bno=#{bno}
</delete>
<delete id="delete">
delete from tbl_board
where bno=#{bno}
</delete>
</mapper>
BoardDAOImpl
package com.example.persistence;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.example.domain.BoardVO;
@Repository
public class BoardDAOImpl implements BoardDAO{
@Inject
SqlSession session;
String namespace="BoardMapper";
@Override
public List<BoardVO> list() {
// TODO Auto-generated method stub
return session.selectList(namespace +".list");
}
@Override
public void insert(BoardVO vo) {
// TODO Auto-generated method stub
session.insert(namespace+".insert",vo);
}
@Override
public void addAttach(String filename) {
// TODO Auto-generated method stub
session.insert(namespace+".addAttach",filename);
}
@Override
public BoardVO read(int bno) {
// TODO Auto-generated method stub
return session.selectOne(namespace+".read",bno);
}
@Override
public List<String> getAttach(int bno) {
// TODO Auto-generated method stub
return session.selectList(namespace+".getAttach",bno);
}
@Override
public void update(BoardVO vo) {
// TODO Auto-generated method stub
session.update(namespace+".update",vo);
}
@Override
public void replaceAttach(int bno, String fileName) {
// TODO Auto-generated method stub
HashMap<String,Object> map=new HashMap<String,Object>();
map.put("bno",bno);
map.put("fileName", fileName);
session.update(namespace+".replaceAttach",map);
}
@Override
public void deleteAttach(int bno) {
// TODO Auto-generated method stub
session.delete(namespace+".deleteAttach",bno);
}
@Override
public void delete(int bno) {
// TODO Auto-generated method stub
session.delete(namespace+".delete",bno);
}
}
BoardController
package com.example.web;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.domain.BoardVO;
import com.example.persistence.BoardDAO;
import com.example.service.BoardService;
@Controller
public class BoardController {
@Inject
BoardDAO dao;
@Inject
BoardService service;
@RequestMapping("list")
public String list(Model model){
model.addAttribute("list",dao.list());
return "list";
}
@RequestMapping("insert")
public String insert() {
return "insert";
}
@RequestMapping(value="insert",method=RequestMethod.POST)
public String insert(BoardVO vo){
service.insert(vo);
System.out.println(vo.toString());
return "redirect:list";
}
@RequestMapping("read")
public String read(int bno,Model model){
model.addAttribute("vo",dao.read(bno));
return "read";
}
@ResponseBody
@RequestMapping("getAttach")
public List<String> getAttach(int bno){
return dao.getAttach(bno);
}
@RequestMapping("update")
public String update(int bno,Model model){
model.addAttribute("vo",dao.read(bno));
return "update";
}
@RequestMapping(value="update",method=RequestMethod.POST)
public String update(BoardVO vo){
service.update(vo);
return "redirect:read?bno=" + vo.getBno();
}
@RequestMapping(value="delete",method=RequestMethod.POST)
public String delete(int bno){
service.delete(bno);
return "redirect:list";
}
}
FileController
package com.example.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;
import javax.annotation.Resource;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@Resource(name="uploadPath")
private String path;
//파일업로드 메소드
private String uploadFile(String originalName, byte[] fileData)throws Exception{
UUID uid = UUID.randomUUID();
String savedName = uid.toString() + "_" + originalName;
File target = new File(path, savedName);
FileCopyUtils.copy(fileData, target);
return savedName;
}
//이미지파일 출력
@ResponseBody
@RequestMapping("/display")
public byte[] display(String fileName)throws Exception{
InputStream in=new FileInputStream(path + "/" + fileName);
byte[] image=IOUtils.toByteArray(in);
in.close();
return image;
}
@ResponseBody
@RequestMapping(value="upload",method=RequestMethod.POST)
public String upload(MultipartFile file)throws Exception{
System.out.println("file:" + file.getOriginalFilename());
String savedName=uploadFile(file.getOriginalFilename(),file.getBytes());
return savedName;
}
//파일삭제
@ResponseBody
@RequestMapping(value="deleteFile",method=RequestMethod.POST)
public void delete(String fileName){
new File(path +"/" +fileName).delete();
}
//파일 다운로드
@ResponseBody
@RequestMapping(value="downloadFile")
public ResponseEntity<byte[]> downloadFile(String fileName)throws Exception{
System.out.println("파일이름:" + fileName);
ResponseEntity<byte[]> entity=null;
InputStream in = null;
try{
HttpHeaders headers = new HttpHeaders();
in= new FileInputStream(path+ "/" + fileName);
fileName = fileName.substring(fileName.indexOf("_") + 1);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.add("Content-Disposition", "attachment;filename=\"" +
new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + "\"");
entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
}catch(Exception e){
System.out.println(e.toString());
entity= new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST);
}finally{
in.close();
}
return entity;
}
}
BoardService
package com.example.service;
import com.example.domain.BoardVO;
public interface BoardService {
public void insert(BoardVO vo);
public void update(BoardVO vo);
public void delete(int bno);
}
BoardServiceImpl
package com.example.service;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.domain.BoardVO;
import com.example.persistence.BoardDAO;
@Service
public class BoardServiceImpl implements BoardService{
@Inject
BoardDAO dao;
@Transactional
@Override
public void insert(BoardVO vo) {
// TODO Auto-generated method stub
dao.insert(vo);
if(vo.getFiles()==null) {return;}
for(String fileName:vo.getFiles()){
dao.addAttach(fileName);
}
}
@Transactional
@Override
public void update(BoardVO vo) {
// TODO Auto-generated method stub
dao.update(vo);
dao.deleteAttach(vo.getBno());
if(vo.getFiles()==null) {return;}
for(String fileName:vo.getFiles()){
dao.replaceAttach(vo.getBno(), fileName);;
}
}
@Transactional
@Override
public void delete(int bno) {
// TODO Auto-generated method stub
dao.deleteAttach(bno);
dao.delete(bno);
}
}
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ 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">
<title>Insert title here</title>
</head>
<body>
<h1>List</h1>
<div style="text-align:center; margin-bottom:20px;">
<button onClick="location.href='insert'" style="border:none;padding:5px;">등록</button>
</div>
<table border=1 width=100>
<c:forEach items="${list}" var="vo">
<tr>
<td>${vo.bno}</td>
<td><a href="read?bno=${vo.bno}">${vo.title}</a></td>
<td><fmt:formatDate value="${vo.regdate}" pattern="yyyy-MM-dd"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
insert.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.js"></script>
</head>
<body>
<form name="frm" action="insert" method="post">
<table border=1 width=600>
<tr>
<td>제목</td>
<td><input type="text"name="title" id="title"></td>
</tr>
<tr>
<td>내용</td>
<td><input type="text"name="content" id="content"></td>
</tr>
</table>
<input type="submit" value="등록" >
<input type="reset" value="취소">
<input type="button" value="목록" onClick="location.href='list'">
<h1>파일첨부</h1>
<div style="width:500px;border:1px solid;padding:5px;">
<input type="file" id="file" accept="image/*">
</div>
<div style="width:500px;border:1px solid;padding:5px;margin-top:10px;">
<ul id="uploaded"></ul>
<script id="temp" type="text/x-handlebars-template">
<li>
<img src="display?fileName={{fullName}}" width=50/>
<a href="{{fullName}}">x</a>
<input type="text" name="files" value="{{fullName}}">
</li>
</script>
</div>
</form>
</body>
<script>
$("#file").on("change",function(){
var file=$("#file")[0].files[0]
//alert(file);
var formData=new FormData();
formData.append("file",file);
$.ajax({
type:"post",
url:"upload",
data:formData,
processData:false,
contentType:false,
success:function(data){
//alert("성공");
var temp=Handlebars.compile($("#temp").html());
dataTemp={"fileName":file.name,"fullName":data},
$("#uploaded").append(temp(dataTemp));
}
});
});
$("#uploaded").on("click","li a",function(e){
var li=$(this).parent();
e.preventDefault();
var fileName=$(this).attr("href");
//alert(fileName);
$.ajax({
type:"post",
url:"deleteFile",
data:{"fileName":fileName},
success:function(data){
alert("삭젴ㅋㅋ");
li.remove();
}
});
});
$(frm).submit(function(){
var title=frm.title.value;
if(title==""){
alert("제목을 입력하세요!");
$(frm.title).focus();
return false;
}
});
</script>
</html>
read.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.js"></script>
</head>
<body>
<h2>Read</h2>
<form name="frm" action="update">
<input type="hidden" value="${vo.bno}" name="bno"/>
<table border=1 width=600>
<tr>
<td>제목</td>
<td><input type="text"name="title" id="title" value="${vo.title}" readonly></td>
</tr>
<tr>
<td>내용</td>
<td><input type="text"name="content" id="content" value="${vo.content}" readonly></td>
</tr>
</table>
<input type="submit" value="수정">
<input type="button" value="목록" onClick="location.href='list'">
<input type="button" value="삭제" onClick="fundel()">
<h1>파일첨부</h1>
<div style="width:500px;border:1px solid;padding:5px;margin-top:10px;">
<ul id="uploaded"></ul>
<script id="temp" type="text/x-handlebars-template">
<li data-src="{{fullName}}">
<img src="display?fileName={{fullName}}" width=50/>
<a href="downloadFile?fileName={{fullName}}">{{fileName}}</a>
</li>
</script>
</div>
</form>
</body>
<script>
//첨부파일 읽기
var bno="${vo.bno}";
getAttach();
//게시글 삭제 버튼
function fundel(){
//alert("ㅎ");
if(!confirm("정말 삭제하시겠습니까?")) return;
frm.action="delete";
frm.method="post";
frm.submit();
$("#uploaded li").each(function(){
var fileName=$(this).attr("data-src");
$.ajax({
type:"post",
url:"deleteFile",
data:{"fileName":fileName},
success:function(){
alert("삭제성공!");
}
});
});
}
function getAttach(){
$.ajax({
type:"get",
url:"getAttach",
data:{"bno":bno},
success:function(data){
var temp=Handlebars.compile($("#temp").html());
$(data).each(function(){
var idx=this.indexOf("_")+1;
var fileName=this.substring(idx);
tempData={"fullName":this,"fileName":fileName};
$("#uploaded").append(temp(tempData));
});
}
});
}
</script>
</html>
update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.js"></script>
</head>
<body>
<h2>update</h2>
<form name="frm" action="update" method="post">
<input type="hidden" value="${vo.bno}" name="bno">
<table border=1 width=600>
<tr>
<td>제목</td>
<td><input type="text"name="title" id="title" value="${vo.title}"></td>
</tr>
<tr>
<td>내용</td>
<td><input type="text"name="content" id="content" value="${vo.content}"></td>
</tr>
</table>
<input type="submit" value="수정">
<input type="button" value="목록" onClick="location.href='list'">
<h1>파일첨부</h1>
<div>
<input type="file" id="file">
</div>
<div style="width:500px;border:1px solid;padding:5px;margin-top:10px;">
<ul id="uploaded"></ul>
<script id="temp" type="text/x-handlebars-template">
<li>
<img src="display?fileName={{fullName}}" width=50/>
<a href="downloadFile?fileName={{fullName}}">{{fileName}}</a>
<a class="del" href="{{fullName}}">x</a>
<input type="text" value="{{fullName}}" name="files">
</li>
</script>
</div>
</form>
</body>
<script>
var bno="${vo.bno}";
getAttach();
//파일 삭제
$("#uploaded").on("click","li .del",function(e){
e.preventDefault();
var fileName=$(this).attr("href");
var li=$(this).parent();
$.ajax({
type:"post",
url:"deleteFile",
data:{"fileName":fileName},
success:function(){
alert("삭제되었습니다.");
li.remove();
}
});
});
//파일 첨부
$("#file").on("change",function(){
var file=$("#file")[0].files[0];
//alert(file.name);//file이라고 하면 object가 뜸
var formData=new FormData();
formData.append("file",file);
$.ajax({
type:"post",
url:"upload",
data:formData,
processData:false,
contentType:false,
success:function(data){
var temp=Handlebars.compile($("#temp").html());
var idx=data.indexOf("_")+1;
var fileName=data.substring(idx);
tempData={"fullName":data,"fileName":fileName};
$("#uploaded").append(temp(tempData));
}
});
});
//첨부파일 읽기
function getAttach(){
$.ajax({
type:"get",
url:"getAttach",
data:{"bno":bno},
success:function(data){
var temp=Handlebars.compile($("#temp").html());
$(data).each(function(){
var idx=this.indexOf("_")+1;
var fileName=this.substring(idx);
tempData={"fullName":this,"fileName":fileName};
$("#uploaded").append(temp(tempData));
});
}
});
}
</script>
</html>
'spring' 카테고리의 다른 글
Controller Tip (0) | 2019.12.06 |
---|---|
프로필 사진 수정하기 (0) | 2019.12.06 |
파일업로드 클래스 (0) | 2019.12.05 |
파일업로드 (0) | 2019.11.29 |
파일업로드 (0) | 2019.11.29 |