SpringBoot 게시판 만들기

스프링부트(SpringBoot) 게시판 만들기10 - Multipart 파일 다운로드

dev109 2017. 9. 5.
반응형

Multipart 파일 다운로드




1. DB에 저장되어 있는 파일정보를 불러오기 위해 mapper, service 추가


1
2
3
4
com.example.demo.board.mapper.BoardMapper.java
 
//파일 상세
public FileVO fileDetail(int bno) throws Exception;
cs


1
2
3
4
5
6
7
8
9
com.example.demo.board.mapper.BoardMapper.xml
 
<select id="fileDetail" parameterType="int" resultType="com.example.demo.board.domain.FileVO">
    SELECT
        *
    FROM Files
    WHERE
        BNO = #{bno}
</select>
cs


1
2
3
4
5
6
com.example.demo.board.service.BoardService.java
 
public FileVO fileDetailService(int bno) throws Exception{
        
    return mBoardMapper.fileDetail(bno);
}
cs





2. BoardController.java 에 boardDetail() 수정


1
2
3
4
5
6
7
8
@RequestMapping("/detail/{bno}"
private String boardDetail(@PathVariable int bno, Model model) throws Exception{
        
    model.addAttribute("detail", mBoardService.boardDetailService(bno));
    model.addAttribute("files", mBoardService.fileDetailService(bno)); //추가
        
    return "detail";
}
cs





3. detail.jsp 수정


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<%@ 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>Detail</title>
</head>
<body>
 
 
<h2> 게시글 상세 </h2>
 
<button class="btn btn-primary" onclick="location.href='/update/${detail.bno}'">수정</button<!-- 추가 -->
<button class="btn btn-danger" onclick="location.href='/delete/${detail.bno}'">삭제</button>  <!-- 추가 -->
 
<div class="container">
    <form action="/insertProc" method="post">
      <div class="form-group">
        <label>제목</label>
        <p>${detail.subject}</p>
      </div>
      <div class="form-group">
        <label>작성자</label>
        <p>${detail.writer}</p>
      </div>
      <div class="form-group">
        <label>작성날짜</label>
        <p>${detail.reg_date}</p>
      </div>
      <div class="form-group"<!-- 첨부파일 다운로드 -->
        <label>첨부파일</label>
        <p><a href="/fileDown/${files.bno}">${files.fileOriName}</a></p>
      </div>                    <!-- //첨부파일 다운로드 -->
      <div class="form-group">
        <label>내용</label>
        <p>${detail.content}</p>
      </div>
      <button type="submit" class="btn btn-primary">작성</button>
    </form>
</div>
 
 
<%@ include file="bootstrap.jsp" %>
</body>
</html>
cs





4. BoardController.java에 파일 다운로드 처리할 메서드 추가


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
@RequestMapping("/fileDown/{bno}")
    private void fileDown(@PathVariable int bno, HttpServletRequest request, HttpServletResponse response) throws Exception{
        
        request.setCharacterEncoding("UTF-8");
        FileVO fileVO = mBoardService.fileDetailService(bno);
        
        //파일 업로드된 경로 
        try{
            String fileUrl = fileVO.getFileUrl();
            fileUrl += "/";
            String savePath = fileUrl;
            String fileName = fileVO.getFileName();
            
            //실제 내보낼 파일명 
            String oriFileName = fileVO.getFileOriName();
            InputStream in = null;
            OutputStream os = null;
            File file = null;
            boolean skip = false;
            String client = "";
            
            //파일을 읽어 스트림에 담기  
            try{
                file = new File(savePath, fileName);
                in = new FileInputStream(file);
            } catch (FileNotFoundException fe) {
                skip = true;
            }
            
            client = request.getHeader("User-Agent");
            
            //파일 다운로드 헤더 지정 
            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Description""JSP Generated Data");
            
            if (!skip) {
                // IE
                if (client.indexOf("MSIE"!= -1) {
                    response.setHeader("Content-Disposition""attachment; filename=\""
                            + java.net.URLEncoder.encode(oriFileName, "UTF-8").replaceAll("\\+""\\ "+ "\"");
                    // IE 11 이상.
                } else if (client.indexOf("Trident"!= -1) {
                    response.setHeader("Content-Disposition""attachment; filename=\""
                            + java.net.URLEncoder.encode(oriFileName, "UTF-8").replaceAll("\\+""\\ "+ "\"");
                } else {
                    // 한글 파일명 처리
                    response.setHeader("Content-Disposition",
                            "attachment; filename=\"" + new String(oriFileName.getBytes("UTF-8"), "ISO8859_1"+ "\"");
                    response.setHeader("Content-Type""application/octet-stream; charset=utf-8");
                }
                response.setHeader("Content-Length""" + file.length());
                os = response.getOutputStream();
                byte b[] = new byte[(int) file.length()];
                int leng = 0;
                while ((leng = in.read(b)) > 0) {
                    os.write(b, 0, leng);
                }
            } else {
                response.setContentType("text/html;charset=UTF-8");
                System.out.println("<script language='javascript'>alert('파일을 찾을 수 없습니다');history.back();</script>");
            }
            in.close();
            os.close();
        } catch (Exception e) {
            System.out.println("ERROR : " + e.getMessage());
        }
        
    }
cs





5. 프로젝트 재실행 후 확인







6. 업로드한 파일 다운로드 끝~~~

반응형

댓글

💲 추천 글