본문 바로가기
Java/Servlet & JSP

JSP) 파일 다운로드

by 박채니 2022. 7. 4.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


파일 다운로드

 

boardView.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/views/common/header.jsp" %>
<%
	Board board = (Board)request.getAttribute("board");
	List<Attachment> attachments = ((BoardExt) board).getAttachments();
%>
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/board.css" />
<section id="board-container">
	<h2>게시판</h2>
	<table id="tbl-board-view">
		<tr>
			<th>글번호</th>
			<td><%= board.getNo() %></td>
		</tr>
		<tr>
			<th>제 목</th>
			<td><%= board.getTitle() %></td>
		</tr>
		<tr>
			<th>작성자</th>
			<td><%= board.getWriter() %></td>
		</tr>
		<tr>
			<th>조회수</th>
			<td><%= board.getReadCount() %></td>
		</tr>
			<% if(attachments != null && !attachments.isEmpty()) {
				for(Attachment attach : attachments) { %>
		<tr>
			<th>첨부파일</th>
			<td>
				<%-- 첨부파일이 있을경우만, 이미지와 함께 original파일명 표시 --%>
				<img alt="첨부파일" src="<%=request.getContextPath() %>/images/file.png" width=16px>
				<a href="<%= request.getContextPath()%>/board/fileDownload?no=<%=attach.getNo()%>"><%= attach.getOriginalFilename() %></a>
			</td>
		</tr>
			<% 	}
			} %>
		<tr>
			<th>내 용</th>
			<td><%= board.getContent() %></td>
		</tr>
		<% 
		boolean canEdit = loginMember != null && (loginMember.getMemberId().equals(board.getWriter()) || loginMember.getMemberRole() == MemberRole.A);
		if(canEdit) { %>
		<tr>
			<%-- 작성자와 관리자만 마지막행 수정/삭제버튼이 보일수 있게 할 것 --%>
			<th colspan="2">
				<input type="button" value="수정하기" onclick="updateBoard()">
				<input type="button" value="삭제하기" onclick="deleteBoard()">
			</th>
		</tr>
		<% } %>
	</table>
</section>
<%@ include file="/WEB-INF/views/common/footer.jsp" %>

 

Controller

BoardFileDownload

@WebServlet("/board/fileDownload")
public class BoardFileDownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BoardService boardService = new BoardService();
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 1. 사용자 입력값 처리
			int no = Integer.parseInt(request.getParameter("no"));
			
			// 2. 업무로직
			// a. attach 조회
			Attachment attach = boardService.findAttachmentByNo(no);
			
			// b. 응답 - 파일 입출력 처리
			// 응답 헤더 contentType : application/octet-stream
			response.setContentType("application/octet-stream"); // 이진데이터일때 사용하는 미디어 타입
			String filename = URLEncoder.encode(attach.getOriginalFilename(), "utf-8"); // 한글파일 깨지지 않도록 인코딩
			response.setHeader("Content-Disposition", "attachment;filename=" + filename); // Content-Disposition : 첨부파일이니까 다운로드해야돼! 알려줌
			
			// 입력 - saveDirectory + renamedFilename
			String saveDirectory = getServletContext().getRealPath("/upload/board");
			File downFile = new File(saveDirectory, attach.getRenamedFilename());
			
			// 출력 - http응답메세지 출력 스트림 response.getOutputStream() -> byte 기반 / response.getWriter() -> 문자기반
			try(
					BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downFile));
					BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())
			) {
				byte[] buffer = new byte[8192]; 	// 8kb 씩 읽어옴
				int len = 0; // 읽어온 byte 수
				while((len = bis.read(buffer)) != -1) {
					bos.write(buffer, 0, len); // buffer에서 0 ~ len까지 출력
				}
			}
			
		} catch(Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
}

다운로드할 파일을 읽어와서 http응답메세지의 출력 스트림 (response.getOutputStream)에 읽어왔습니다.

 

Service

BoardService

public Attachment findAttachmentByNo(int no) {
    Connection conn = getConnection();
    Attachment attach = boardDao.findAttachmentByNo(conn, no);
    close(conn);
    return attach;
}

 

Dao

BoardDao

// findAttachmentByNo = select * from attachment where no = ?
public Attachment findAttachmentByNo(Connection conn, int no) {
    PreparedStatement pstmt = null;
    ResultSet rset = null;
    Attachment attach = null;
    String sql = prop.getProperty("findAttachmentByNo");

    try {
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, no);
        rset = pstmt.executeQuery();
        while(rset.next()) {
            attach = handleAttachmentResultSet(rset);
        }
    } catch (SQLException e) {
        throw new BoardException("첨부파일 1건 조회 오류!", e);
    } finally {
        close(rset);
        close(pstmt);
    }
    return attach;
}

파일 다운로드 완료!