- Jquery로 prompt 쓰기
$('#e').click(function(){
let pwd = prompt("글비밀번호를 입력하세요.");
if(pwd == '${dto.pwd}'){
$('#editForm').show();
} else {
alert('틀렸습니다.');
}
});
$('#d').click(function(){
let pwd = prompt("글비밀번호를 입력하세요.");
if(pwd == '${dto.pwd}'){
location.href='/data/del?num=${dto.num}';
} else {
alert('틀렸습니다.');
}
});
Entity (Downfile.java)
@Id
@SequenceGenerator(name="seq_gen", sequenceName="seq_data", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_data")
private int num;
private String writer; //글 작성자
private String pwd; //글비밀번호
private Date wdate; //작성일
private String title;
private String content; //설명
private int cnt; //다운로드 수
private String path; //자료경로 -- 파일명만 저장했음,,
@PreUpdate
@PrePersist //insert문 실행 전에 먼저 처리
public void sysdate() {
wdate = new Date();
}
package com.example.demo.down;
import java.util.Date;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import jakarta.persistence.SequenceGenerator;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Entity
@Setter
@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Downfile {
@Id
@SequenceGenerator(name="seq_gen", sequenceName="seq_data", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_data")
private int num;
private String writer; //글 작성자
private String pwd; //글비밀번호
private Date wdate; //작성일
private String title;
private String content; //설명
private int cnt; //다운로드 수
private String path; //자료경로
@PreUpdate
@PrePersist //insert문 실행 전에 먼저 처리
public void sysdate() {
wdate = new Date();
}
}
Dto (DownfileDto.java)
public class DownfileDto {
private int num;
private String writer; //글 작성자
private String pwd; //글비밀번호
private Date wdate; //작성일
private String title;
private String content; //설명
private int cnt; //다운로드 수
private String path; //자료경로(파일명)
private MultipartFile file; // 이미지 파일
}
package com.example.demo.down;
import java.util.Date;
import org.springframework.web.multipart.MultipartFile;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class DownfileDto {
private int num;
private String writer; //글 작성자
private String pwd; //글비밀번호
private Date wdate; //작성일
private String title;
private String content; //설명
private int cnt; //다운로드 수
private String path; //자료경로
private MultipartFile file; // 실제 이미지 파일
}
Dao (DownfileDao.java)
@Repository
public interface DownfileDao extends JpaRepository<Downfile, Integer> {
@Transactional
@Modifying
@Query(value="update Downfile set cnt=cnt+1 where num=:num", nativeQuery=true)
void updateCnt(@Param("num") int num);
ArrayList<Downfile> findByTitleLike(String title);
ArrayList<Downfile> findByWriter(String writer);
}
package com.example.demo.down;
import java.util.ArrayList;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import jakarta.transaction.Transactional;
@Repository
public interface DownfileDao extends JpaRepository<Downfile, Integer> {
@Transactional
@Modifying
@Query(value="update Downfile set cnt=cnt+1 where num=:num", nativeQuery=true)
void updateCnt(@Param("num") int num);
ArrayList<Downfile> findByTitleLike(String title);
ArrayList<Downfile> findByWriter(String writer);
}
Service (DownfileService.java)
package com.example.demo.down;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DownfileService {
@Autowired
private DownfileDao dao;
// 자료업로드 글 작성
public int save(DownfileDto dto) {
dao.save(new Downfile(dto.getNum(), dto.getWriter(), dto.getPwd(), dto.getWdate(), dto.getTitle(),
dto.getContent(), dto.getCnt(), dto.getPath()));
return dto.getNum();
}
// 자료글목록 -- 전체 검색
public ArrayList<DownfileDto> getAll() {
ArrayList<Downfile> list = (ArrayList<Downfile>) dao.findAll();
ArrayList<DownfileDto> dtolist = new ArrayList<DownfileDto>();
for (Downfile f : list) {
dtolist.add(new DownfileDto(f.getNum(), f.getWriter(), f.getPwd(), f.getWdate(), f.getTitle(),
f.getContent(), f.getCnt(), f.getPath(), null));
}
return dtolist;
}
// 제목 검색
public ArrayList<DownfileDto> getByTitle(String title) {
ArrayList<Downfile> list = (ArrayList<Downfile>) dao.findByTitleLike("%"+title+"%");
ArrayList<DownfileDto> dtolist = new ArrayList<DownfileDto>();
for (Downfile f : list) {
dtolist.add(new DownfileDto(f.getNum(), f.getWriter(), f.getPwd(), f.getWdate(), f.getTitle(),
f.getContent(), f.getCnt(), f.getPath(), null));
}
return dtolist;
}
// 작성자로 검색
public ArrayList<DownfileDto> getByWriter(String writer) {
ArrayList<Downfile> list = (ArrayList<Downfile>) dao.findByWriter(writer);
ArrayList<DownfileDto> dtolist = new ArrayList<DownfileDto>();
for (Downfile f : list) {
dtolist.add(new DownfileDto(f.getNum(), f.getWriter(), f.getPwd(), f.getWdate(), f.getTitle(),
f.getContent(), f.getCnt(), f.getPath(), null));
}
return dtolist;
}
// 상세페이지 -- 글번호로 검색
public DownfileDto getBoard(int num) {
Downfile f = dao.findById(num).orElse(null);
if (f == null) {
return null;
}
return new DownfileDto(f.getNum(), f.getWriter(), f.getPwd(), f.getWdate(), f.getTitle(), f.getContent(),
f.getCnt(), f.getPath(), null);
}
// 다운로드 -> 1업
public void cntUp(int num) {
dao.updateCnt(num);
}
// 삭제 (자기글만)
public void del(int num) {
dao.deleteById(num);
}
}
Controller (DownfileController.java)
package com.example.demo.down;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/data")
public class DownfileController {
@Autowired
private DownfileService service;
@Value("${spring.servlet.multipart.location}")
private String path;
// 자료업로드 글작성
@GetMapping("/add")
public void addForm(ModelMap map) {
}
@PostMapping("/add")
public String add(DownfileDto dto) {
MultipartFile f = dto.getFile();
String fname = f.getOriginalFilename();
File f2 = new File(path+fname);
try {
f.transferTo(f2);
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dto.setPath(fname);
int num = service.save(dto);
return "redirect:/data/list";
}
// 자료글목록
@GetMapping("/list")
public void list(ModelMap map) {
ArrayList<DownfileDto> list = service.getAll();
map.addAttribute("list", list);
}
@GetMapping("/read_img")
public ResponseEntity<byte[]> read_img(String fname) {
File f = new File(path + fname);
HttpHeaders header = new HttpHeaders(); // HttpHeaders 객체 생성
ResponseEntity<byte[]> result = null; // 선언
try {
header.add("Content-Type", Files.probeContentType(f.toPath()));// 응답 데이터의 종류를 설정
// 응답 객체 생성
result = new ResponseEntity<byte[]>(FileCopyUtils.copyToByteArray(f), header, HttpStatus.OK);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
// 상세페이지
@GetMapping("/detail")
public void detail(int num, ModelMap map) {
DownfileDto dto = service.getBoard(num);
File dir = new File(dto.getPath());
map.addAttribute("dto", dto);
map.addAttribute("file", dir);
}
// 파일 다운로드
@RequestMapping("/down")
public ResponseEntity<byte[]> down(String fname, int num) {
File f = new File(path + fname);// 타겟 파일에 있는 파일을 읽어서
HttpHeaders header = new HttpHeaders();
ResponseEntity<byte[]> result = null;
try {
header.add("Content-Type", Files.probeContentType(f.toPath()));// 마임타입
header.add(HttpHeaders.CONTENT_DISPOSITION,
"attachment;filename=\"" + URLEncoder.encode(fname, "UTF-8") + "\"");
result = new ResponseEntity<byte[]>(FileCopyUtils.copyToByteArray(f), header, HttpStatus.OK);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 다운로드 카운트
service.cntUp(num);
return result;
}
// 수정 (자기글)
@PostMapping("/detail")
public String edit(DownfileDto dto) {
DownfileDto dto2 = service.getBoard(dto.getNum());
dto2.setTitle(dto.getTitle());
dto2.setContent(dto.getContent());
service.save(dto2);
return "redirect:/data/detail?num="+dto.getNum();
}
// 삭제 (자기글)
@GetMapping("/del")
public String del(int num) {
DownfileDto dto = service.getBoard(num);
String delPath = path + dto.getPath();
File delFile = new File(delPath);
delFile.delete(); // 저장된 파일 삭제
service.del(num); // DB 삭제
return "redirect:/data/list";
}
}
add.jsp
<tr><th>파일</th><td><input type="file" name="file"></td></tr>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>파일 업로드</h3>
<form action="/data/add" method="post" enctype="multipart/form-data">
<table border="1">
<tr><th>작성자</th><td><input type="text" name="writer"></td></tr>
<tr><th>비밀번호</th><td><input type="text" name="pwd"></td></tr>
<tr><th>제목</th><td><input type="text" name="title"></td></tr>
<tr><th>설명</th><td><textarea name="content" rows="5" cols="30"></textarea></td></tr>
<tr><th>파일</th><td><input type="file" name="file"></td></tr>
<tr><th>등록</th><td><input type="submit" value="등록"></td></tr>
</table>
</form>
</body>
</html>
list.jsp
<%@ 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>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>자료실</h3>
<a href="/data/add">글작성</a>
<table border="1">
<tr><th>file</th><th>writer</th><th>title</th><th>down</th></tr>
<c:forEach var="dto" items="${list }">
<tr>
<td><img src="/data/read_img?fname=${dto.path}" width="100" height="100"></td>
<td>${dto.writer}</td>
<td><a href="/data/detail?num=${dto.num}">${dto.title}</a></td>
<td>${dto.cnt}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
detail.jsp
<!-- 이미지 파일 보여주기 -->
<img src="/data/read_img?fname=${dto.path}" width="200" height="150">
<!-- 파일 다운로드 -->
파일: <a href="/data/down?fname=${dto.path}&num=${dto.num}">${file}</a>
<%@ 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>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#editForm').hide();
$('#e').click(function(){
let pwd = prompt("글비밀번호를 입력하세요.");
if(pwd == '${dto.pwd}'){
$('#editForm').show();
} else {
alert('틀렸습니다.');
}
});
$('#d').click(function(){
let pwd = prompt("글비밀번호를 입력하세요.");
if(pwd == '${dto.pwd}'){
location.href='/data/del?num=${dto.num}';
} else {
alert('틀렸습니다.');
}
});
});
</script>
</head>
<body>
<h3>${dto.title }</h3>
<img src="/data/read_img?fname=${dto.path}" width="200" height="150">
<ul>
<li>작성자: ${dto.writer }</li>
<li>작성일: ${dto.wdate }</li>
<li>설명: ${dto.content }</li>
<li>다운수: ${dto.cnt }</li>
<li>파일: <a href="/data/down?fname=${dto.path}&num=${dto.num}">${file}</a></li>
</ul>
<input type="button" value="수정" id="e">
<input type="button" value="삭제" id="d">
<div id="editForm">
<form action="/data/detail" method="post" id="f">
<table>
<tr><td>제목</td><td><input type="text" name="title" value="${dto.title }"></td></tr>
<tr><td>내용</td><td><textarea name="content" rows="5" cols="30">${dto.content }</textarea></td></tr>
</table>
<input type="hidden" name="num" value="${dto.num}">
<input type="submit" value="수정완료">
</form>
</div>
</body>
</html>
https://intheham.tistory.com/98
[Spring JPA] 이미지 파일 1개 업로드
1. application.properties에 #multipart 추가하기 # port server.port=8081 # JSP view spring.mvc.view.prefix=/WEB-INF/views/ spring.mvc.view.suffix=.jsp # oracle set spring.datasource.driver-class-name=oracle.jdbc.OracleDriver spring.datasource.url=jdbc:
intheham.tistory.com
https://intheham.tistory.com/100
[Spring JPA] 이미지 파일 여러개 업로드
https://intheham.tistory.com/98 [Spring JPA] 이미지 파일 1개 업로드 1. application.properties에 #multipart 추가하기 # port server.port=8081 # JSP view spring.mvc.view.prefix=/WEB-INF/views/ spring.mvc.view.suffix=.jsp # oracle set spring.data
intheham.tistory.com
https://intheham.tistory.com/99
[Spring & JPA] 파일 다운로드
https://intheham.tistory.com/72 [JAVA] 파일 다운로드 @WebServlet("/down/test") public class DownTest extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String do
intheham.tistory.com