본문 바로가기

java,jsp,spring/JSP

JSP 게시판 - 파일 다운로드

1.BoardBean.java - 속성 추가

private String b_rfname;
	
	public String getB_rfname() {
		return b_rfname;
	}
	public void setB_rfname(String b_rfname) {
		this.b_rfname = b_rfname;
	}

2.BoardDBBean.java - 메소드 수정 및 추가

public int insertBoard(BoardBean board) throws Exception {
		String sql = "SELECT MAX(B_ID) FROM boardT"; // id 최대값

		int re = -1;
		int number;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int id = board.getB_id();
		int ref = board.getB_ref();
		int step = board.getB_step();
		int level = board.getB_level();
		int count = 0;
		try {
			conn = getConnection();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();

			if (rs.next()) {
				number = rs.getInt(1) + 1;
			} else {
				number = 1;
			}
			
			if (id != 0) { // 답변 글쓰기 이면 업데이트 쿼리 실행
				sql = "UPDATE boardT SET B_STEP = B_STEP+1 WHERE B_REF = ? AND B_STEP > ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, ref);
				pstmt.setInt(2, step);
				pstmt.executeUpdate();
				step = step + 1;
				level = level + 1;
			} else {
				ref = number;
				step = 0;
				level = 0;
			}
			sql = "INSERT INTO boardT VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			pstmt = conn.prepareStatement(sql);

			pstmt.setInt(1, number);
			pstmt.setString(2, board.getB_name());
			pstmt.setString(3, board.getB_email());
			pstmt.setString(4, board.getB_title());	
			pstmt.setString(5, board.getB_content());
			pstmt.setTimestamp(6, board.getB_date());
			pstmt.setInt(7, board.getB_hit());
			// 조회수 컬럼의 초기값을 0으로 설정 > 데이터 구조에서 디폴트값을 0으로 설정(글쓰면 조회수 0이기 때문)
			pstmt.setString(8, board.getB_pwd());
			pstmt.setString(9, board.getB_ip());
			pstmt.setInt(10, ref);
			pstmt.setInt(11, step);
			pstmt.setInt(12, level);
			pstmt.setString(13, board.getB_fname());
			pstmt.setInt(14, board.getB_fsize()); // 파일 크기
			pstmt.setString(15, board.getB_rfname()); // 파일 이름
			pstmt.executeUpdate();
			
			re=1;
		} catch (SQLException ex) {
			System.out.print("글쓰기 실패");
			ex.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return re;
	}

public BoardBean getBoard(int b_id, boolean hitAdd) throws Exception {
		String sql = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		BoardBean bb = null;
		
		try {
			if (hitAdd == true) { // 게시글 볼때는 true, 수정할 때는 false
				sql = "UPDATE boardT SET B_HIT=B_HIT+1 WHERE B_ID = ?";
				// 조회수 수정하는 쿼리문 해당 메소드가 실행될 때 조회수 1씩 증가해서 업데이트 쿼리 실행
				conn = getConnection();
				;
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, b_id);
				pstmt.executeUpdate(); // 쿼리 실행
			} else {
				conn = getConnection();
			}
			
			sql = "SELECT B_ID, B_EMAIL, B_TITLE, B_NAME, B_CONTENT, B_DATE, B_HIT, B_PWD"
					+ ", B_IP, B_REF, B_STEP, B_LEVEL, B_FNAME, B_FSIZE, B_RFNAME FROM boardT where B_ID = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, b_id);
			rs = pstmt.executeQuery();

			if (rs.next()) {
				bb = new BoardBean();
				bb.setB_id(b_id);
				bb.setB_name(rs.getString("B_NAME"));
				bb.setB_email(rs.getString("B_EMAIL"));
				bb.setB_title(rs.getString("B_TITLE"));
				bb.setB_content(rs.getString("B_CONTENT"));
				bb.setB_date(rs.getTimestamp("B_DATE"));
				bb.setB_hit(rs.getInt("B_HIT"));
				bb.setB_pwd(rs.getString("B_PWD"));
				bb.setB_ip(rs.getString("B_IP"));
				bb.setB_ref(rs.getInt("B_REF"));
				bb.setB_step(rs.getInt("B_STEP"));
				bb.setB_level(rs.getInt("B_LEVEL"));
				bb.setB_fname(rs.getString("B_FNAME"));
				bb.setB_fsize(rs.getInt("B_FSIZE"));
				bb.setB_rfname(rs.getString("B_RFNAME"));
			}
		} catch (SQLException ex) {
			System.out.print("조회 실패");
			ex.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return bb;
	}
public BoardBean getFileName(int b_id) throws Exception {
		String sql = "SELECT B_FNAME, B_RFNAME FROM boardT where B_ID = ?";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		BoardBean bb = null;
		try {
			conn = getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, b_id);
			rs = pstmt.executeQuery();

			if (rs.next()) {
				bb = new BoardBean();
				bb.setB_fname(rs.getString("B_FNAME"));
				bb.setB_rfname(rs.getString("B_RFNAME"));
			}
		} catch (SQLException ex) {
			System.out.print("조회 실패");
			ex.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return bb;
	}

3.write_ok.jsp - 업로드 방식 변경

<%@page import="java.util.Enumeration"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="com.jspsmart.upload.File"%>
<%@page import="java.net.InetAddress"%>
<%@page import="magic.board.BoardDBBean"%>
<%@page import="java.sql.Timestamp"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8"); %>
<jsp:useBean class="magic.board.BoardBean" id="board"></jsp:useBean>
<jsp:setProperty property="*" name="board"/>
<%
	String path = request.getRealPath("upload");
	int size = 1024*1024; // 1MB로 크기 제한
	int fileSize = 0;
	String file = "";
	String oriFile = "";
	MultipartRequest multi = new MultipartRequest(request, path, size, "UTF-8", new DefaultFileRenamePolicy());
	// DefaultFileRenamePolicy : 파일 이름 중복이면 변경
	Enumeration files = multi.getFileNames();
	String str = (String)files.nextElement();
	file = multi.getFilesystemName(str); // 파일 이름을 가져옴 
	
	if(file != null){
		oriFile = multi.getOriginalFileName(str); // 원본 이름
		fileSize = file.getBytes().length;
	}
%>
<%
	InetAddress address = InetAddress.getLocalHost();
	String ip = address.getHostAddress();
	String content = multi.getParameter("b_content");
	content = content.replace("\r\n", "<br>"); 
	
	board.setB_name(multi.getParameter("b_name"));
	board.setB_email(multi.getParameter("b_email"));
	board.setB_title(multi.getParameter("b_title"));
	board.setB_content(content);
	board.setB_pwd(multi.getParameter("b_pwd"));
	board.setB_id(Integer.parseInt(multi.getParameter("b_id")));
	board.setB_ref(Integer.parseInt(multi.getParameter("b_ref")));
	board.setB_step(Integer.parseInt(multi.getParameter("b_step")));
	board.setB_level(Integer.parseInt(multi.getParameter("b_level")));

	board.setB_date(new Timestamp(System.currentTimeMillis()));
	board.setB_ip(ip);

	if(file != null){
		board.setB_fname(file);
		board.setB_fsize(fileSize);
		board.setB_rfname(oriFile);
	}

	BoardDBBean db = BoardDBBean.getInstance();
	int re = db.insertBoard(board);
	
	if(re == 1){
		response.sendRedirect("list.jsp");
	}else{
		response.sendRedirect("write.jsp");
	}
%>

4.show.jsp - 파일 다운로드 변경

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="magic.board.BoardBean"%>
<%@page import="magic.board.BoardDBBean"%>
<%@ 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>
<%
	BoardDBBean bdb = BoardDBBean.getInstance();
	BoardBean bb = bdb.getBoard(Integer.parseInt(request.getParameter("b_id")),true);
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	String pageNum = request.getParameter("pageNum");
%>
	<center>
		<h1>글 내 용 보 기</h1>
		<table border="1" width="600" cellspacing="0">
			<tr height="30" align="center">
				<td width="100">글번호</td>
				<td width="200"><%= bb.getB_id() %></td>
				<td width="100">조회수</td>
				<td width="200"><%= bb.getB_hit() %></td>
			</tr>
			<tr height="30" align="center">
				<td width="100" >작성자</td>
				<td width="200"><%= bb.getB_name() %></td>
				<td width="100" >작성일</td>
				<td width="200"><%= sdf.format(bb.getB_date()) %></td>
			<tr height="30">
				<td width="100" align="center">파 일</td>
				<td colspan="3">
					<%
						out.print("<p>첨부파일 "+"<a href='FileDownload.jsp?fileNum="+bb.getB_id()+"'>"+bb.getB_rfname()+"</a></p>");
					%>
				</td>
			</tr>
			<tr height="30">
				<td width="100" align="center">글제목</td>
				<td width="200" colspan="3"><%= bb.getB_title() %></td>
			</tr>
			<tr height="30">
				<td width="100" align="center">글내용</td>
				<td width="200" colspan="3"><%= bb.getB_content() %></td>
			</tr>
			<tr height="30">
				<td colspan="4" align="right">
					<input type="button" value="글수정" onclick="location.href='edit.jsp?b_id=<%= bb.getB_id() %>&pageNum=<%= pageNum %>'" />
					&nbsp;&nbsp;&nbsp;&nbsp;
					<input type="button" value="글삭제" onclick="location.href='delete.jsp?b_id=<%= bb.getB_id() %>&pageNum=<%= pageNum %>'" />
					&nbsp;&nbsp;&nbsp;&nbsp;
					<input type="button" value="답변글" onclick="location.href='write.jsp?b_id=<%= bb.getB_id() %>&pageNum=<%= pageNum %>'" />
					&nbsp;&nbsp;&nbsp;&nbsp;
					<input type="button" value="글목록" onclick="location.href='list.jsp?pageNum=<%= pageNum %>'" />
				</td>
			</tr>
		</table>
	</center>
</body>
</html>

5.FileDownload.jsp

<%@page import="java.io.BufferedOutputStream"%>
<%@page import="java.io.BufferedInputStream"%>
<%@page import="magic.board.BoardBean"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.File"%>
<%@page import="magic.board.BoardDBBean"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	int bid = Integer.parseInt(request.getParameter("fileNum"));
	BoardDBBean bdb = BoardDBBean.getInstance();
	BoardBean board = bdb.getFileName(bid);
	
	String fName = "";
	String rfName = "";
	if(board != null) {
		fName = board.getB_fname();
		rfName = board.getB_rfname();
	}
	
	String saveDirectory = application.getRealPath("/upload"); // 저장 경로
	String fPath = saveDirectory + File.separator + fName; // separator : 경로 구분자 '/' '\'
	
	File file = new File(fPath);
	long length = file.length();
	rfName = new String(rfName.getBytes("ms949"), "8859_1"); // ms949 : 한글 인코딩
	
	
	response.setContentType("application/octet-stream"); // 8비트로 된 데이터(지정되지 않은 파일 형식)
	response.setContentLength((int)length);
	response.setHeader("Content-Disposition", "attachment;filename=" + rfName); // 파일 링크를 클릭했을때 다운로드 화면이 출력되게 처리함
	
	BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
	
	out.clear();
	out = pageContext.pushBody(); // 출력할게 남아 있으면 다 비움
	
	BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

	int data;
	while((data = bis.read()) != -1){ // End of File
		bos.write(data);
	}
	
	bis.close();
	bos.close();
%>

'java,jsp,spring > JSP' 카테고리의 다른 글

JSP 게시판 - 파일 업로드  (1) 2022.09.15
JSP 게시판 페이징  (1) 2022.09.13
JSP 게시판 답글 기능  (1) 2022.09.11
JSP 게시판 (4) 글 삭제  (0) 2022.09.06
JSP 게시판 (3) 글 수정  (0) 2022.09.06