반응형

# MVC07_11 파일 다운로드(한글깨짐 방지)

## 상세보기 시 이미지 표시

  • 로그인 한 경우 본인 정보 상세보기 클릭 시 사진 노출되도록 작업
  • memberContent.jsp에 아래와 같이 작업. ${sessionScope.userName}님이 로그인 하셨습니다. 앞에 이미지 가져오는 코드 추가.
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="kr.bit.model.*" %>    
<%
  // MemberVO vo=(MemberVO)request.getAttribute("vo");
%>    
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<script type="text/javascript">
	function update() {
		document.form1.action="<c:url value='/memberUpdate.do'/>";
		document.form1.submit();
	}
	
	function frmreset() {
		document.form1.reset();
	}
</script>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css'>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js'></script>
</head>
<body>

<div class="container">
	<h2>상세 화면</h2>
	<div class="panel panel-default">
		<div class="panel-heading">
			<c:if test="${sessionScope.userId != null && sessionScope != '' && sessionScope.userId == vo.id}">
				<label>
					<img src="<c:out value='file_repo/${vo.filename}'/>" width="60px" height="60px" />
					${sessionScope.userName}님이 로그인 하셨습니다.
				</label>
			</c:if>
			<c:if test="${sessionScope.userId == null || sessionScope == '' }">
				<label>안녕하세요.</label>
			</c:if>	
		</div>
		<div class="panel-body">
		<form id="form1" name="form1" class="form-horizontal" method="post">
		<input type="hidden" name="num" value="${vo.num}"/>
			<div class="form-group">
				<label class="control-Label col-sm-2">번호 :</label>
				<div class="col-sm-10">
					<c:out value="${vo.num}"/>
				</div>
			</div>
			<div class="form-group">
				<label class="control-Label col-sm-2">아이디 :</label>
				<div class="col-sm-10">
					<c:out value="${vo.id}"/>
				</div>
			</div>
			<div class="form-group">
				<label class="control-Label col-sm-2">비밀번호 :</label>
				<div class="col-sm-10">
					<c:out value="${vo.pass}"/>
				</div>
			</div>
			<div class="form-group">
				<label class="control-Label col-sm-2">이름 :</label>
				<div class="col-sm-10">
					<c:out value="${vo.name}"/>
				</div>
			</div>
			<div class="form-group">
				<label class="control-Label col-sm-2">나이 :</label>
				<div class="col-sm-10">
					<input type="text" class="form-control" id="age" name="age" value="${vo.age}" style="width:10%;"/>
				</div>
			</div>
			<div class="form-group">
				<label class="control-Label col-sm-2">이메일 :</label>
				<div class="col-sm-10">
					<input type="text" class="form-control" id="email" name="email" value="${vo.email}" style="width:30%;"/>
				</div>
			</div>
			<div class="form-group">
				<label class="control-Label col-sm-2">전화번호 :</label>
				<div class="col-sm-10">
					<input type="text" class="form-control" id="phone" name="phone" value="${vo.phone}" style="width:30%;"/>
				</div>
			</div>
			<div class="form-group">
				<label class="control-Label col-sm-2">첨부파일 :</label>
				<div class="col-sm-10">
					<input type="file" id="file" name="file" />
					<c:if test="${vo.filename != null && vo.filename != ''}">
						<c:out value='${vo.filename}'/>	
					</c:if>	
					<c:if test="${sessionScope.userId != null && sessionScope.userId == vo.id && vo.filename != null && vo.filename != ''}">
						<span class="glyphicon glyphicon-remove"></span>
					</c:if>				
				</div>
			</div>			
		</form>
		</div>
		<div class="panel-footer" style="text-align: center;">
			<c:if test="${!empty sessionScope.userId}">
				<c:if test="${sessionScope.userId == vo.id}">
					<input type="button" value="수정하기" class='btn btn-primary' onclick="update()"/>
				</c:if>
				<c:if test="${sessionScope.userId != vo.id}">
					<input type="button" value="수정하기" class='btn btn-primary' onclick="update()" disabled="disabled"/>
				</c:if>
			</c:if>
			<input type="button" value="취소" class='btn btn-warning' onclick="frmreset()"/>
			<input type="button" value="리스트" onclick="location.href='${ctx}/memberList.do'" class='btn'/>
		</div>
	</div>
</div>
</body>
</html>

## 상세보기 첨부파일 이미지 다운로드

  • 상세보기 첨부파일 이름 클릭 시 이미지 다운받을 수 있도록 작업

1. memberContent.jsp 에 아래와 같이 작업

<script type="text/javascript">
	function getFile(filename) {
		location.href="<c:url value='/fileGet.do'/>?filename=" + filename;
	}
</script>

<div class="form-group">
  <label class="control-Label col-sm-2">첨부파일 :</label>
  <div class="col-sm-10">
  	<input type="file" id="file" name="file" />
    <c:if test="${vo.filename != null && vo.filename != ''}">
    	<a href="javascript:getFile('${vo.filename}')"><c:out value='${vo.filename}'/></a>	
    </c:if>	
    <c:if test="${sessionScope.userId != null && sessionScope.userId == vo.id && vo.filename != null && vo.filename != ''}">
    	<span class="glyphicon glyphicon-remove"></span>
    </c:if>				
  </div>
</div>

2. HandlerMapping

package kr.bit.frontcontroller;

import java.util.HashMap;

import kr.bit.controller.Controller;
import kr.bit.controller.*;

public class HandlerMapping {
  private HashMap<String, Controller> mappings;
  public HandlerMapping() {
	  mappings=new HashMap<String, Controller>();
	  mappings.put("/memberList.do", new MemberListController());
	  mappings.put("/memberInsert.do", new MemberInsertController());
	  mappings.put("/memberRegister.do", new MemberRegisterController());
	  mappings.put("/memberContent.do", new MemberContentController());
	  mappings.put("/memberUpdate.do", new MemberUpdateController());
	  mappings.put("/memberDelete.do", new MemberDeleteController());
	  mappings.put("/memberLogin.do", new MemberLoginController());
	  mappings.put("/memberLogout.do", new MemberLogoutController());
	  mappings.put("/memberDbcheck.do", new MemberDbcheckController());
	  mappings.put("/memberAjaxList.do", new MemberAjaxListController());
	  mappings.put("/memberAjaxDelete.do", new MemberAjaxDeleteController());
	  mappings.put("/fileAdd.do", new FileAddController());
	  mappings.put("/fileGet.do", new FileGetController());
  }
  public Controller getController(String key) { // key=>/memberList.do
	  return mappings.get(key);
  }
}

3. FileGetController 생성

  • 프로젝트 > src > kr.bit.controller 우 클릭 > class > FileGetController 이름으로 생성
  • 다운로드 준비 시 아래 코드 추가
response.setContentLength((int)file.length());
response.setContentType("application/x-msdownload;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + filename + ";");
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
  • 다운로드를 위한 코드는 아래와 같다.
package kr.bit.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileGetController implements Controller {

	@Override
	public String requestHandler(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String filename = request.getParameter("filename");
		
		String UPLOAD_DIR = "file_repo";
		String uploadPath = request.getServletContext().getRealPath("") + File.separator + UPLOAD_DIR;
		
		File file = new File(uploadPath + "\\" + filename);
		
		// 클라이언트로부터 넘어오는 파일 이름에 한글 있는 경우 깨짐 방지.
		filename = URLEncoder.encode(filename, "UTF-8");
		filename = filename.replace("+", " ");
		// 다운로드 준비 (서버에서 클라이언트에게 다운로드 준비 시키는 부분_다운로드 창 띄움)
		response.setContentLength((int)file.length());
		response.setContentType("application/x-msdownload;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + filename + ";");
		response.setHeader("Content-Transfer-Encoding", "binary");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "0");
		
		// 	실제 다운로드를 하는 부분
		FileInputStream in = new FileInputStream(file);	// 파일 읽기 준비
		OutputStream out = response.getOutputStream();
		byte[] buffer = new byte[104];
		
		while ( true ) {
			int count = in.read(buffer);
			
			if ( count == -1 ) {
				break;
			}
			out.write(buffer, 0, count); // 다운로드 (0% ..... 100%)
		}
		
		in.close();
		out.close();
		
		return null;
	}

}

## 다운로드 테스트

  • 영문, 한글, 공백 이름의 파일 업로드, 다운로드 가능
  • 아래와 같이 다운로드 가능!!

반응형

+ Recent posts