JSP + Servlet | 파일 다운로드

파과·2022년 7월 22일
0

JSP + Servlet

목록 보기
28/33
post-custom-banner

참고 : 🔗 MIME 타입

upload.jsp

<%@ 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>
	<form action="upload2.do" method="post" enctype="multipart/form-data">	
		1. 파일 지정하기: <input type="file" name="uploadFile01"><br>
		2. 파일 지정하기: <input type="file" name="uploadFile02"><br>
		3. 파일 지정하기: <input type="file" name="uploadFile03"><br>
		<input type="submit" value="전송">
	</form>
</body>
</html>

MultiUploadServlet.java

package com.sw.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

@WebServlet("/upload2.do")
public class MultiUploadServlet extends HttpServlet {
   private static final long serialVersionUID = 1L;
       
    public MultiUploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // TODO Auto-generated method stub
   }

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // TODO Auto-generated method stub
      
      request.setCharacterEncoding("UTF-8");
      response.setContentType("text/html; charset=UTF-8");
      PrintWriter out = response.getWriter();
      
      HashMap<String, String> map = new HashMap<String, String>();
      
      String savePath = "upload";
      int uploadFileSizeLimit = 5 * 1024 * 1024;
      String encType = "UTF-8";
      ServletContext context = getServletContext();
      String uploadFilePath = context.getRealPath(savePath);
      try {
         MultipartRequest multi = new MultipartRequest(request,
               uploadFilePath, uploadFileSizeLimit, encType,
               new DefaultFileRenamePolicy());
         Enumeration files = multi.getFileNames();
         while (files.hasMoreElements()) {
            String file = (String) files.nextElement();
            String file_name = multi.getFilesystemName(file);
            // 중복된 파일을 업로드할 경우 파일명이 바뀐다.
            String ori_file_name = multi.getOriginalFileName(file);
            
            map.put(file_name,ori_file_name);
//            out.print("<br> 업로드된 파일명 : " + file_name);
//            out.print("<br> 원본 파일명 : " + ori_file_name);
//            out.print("<hr>");
         }
         
         request.setAttribute("map", map);
      } catch (Exception e) {
         System.out.print("예외 발생 : " + e);
      }// catch
      
      RequestDispatcher dispatcher = request.getRequestDispatcher("fileList.jsp");
      dispatcher.forward(request, response);
   }

}

file_down.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.io.*" %>
<%@ page import="com.oreilly.servlet.ServletUtils"%>
<%
   String fileName = request.getParameter("file_name");

   String savePath = "upload";
   ServletContext context = getServletContext();
   String sDownloadPath = context.getRealPath(savePath);
   String sFilePath = sDownloadPath + "\\" + fileName;
   
   byte b[] = new byte[4096];
   File oFile = new File(sFilePath);
   
   FileInputStream in = new FileInputStream(sFilePath);
   
   String sMimeType = getServletContext().getMimeType(sFilePath);
   System.out.println("sMimeType>>>"+sMimeType );
   
   if(sMimeType == null) sMimeType = "application/octet-stream";  //8비트 형식으로 처리
   
   response.setContentType(sMimeType);
   
   String sEncoding = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
   
   //파일 다운로드 창 실행
   response.setHeader("Content-Disposition", "attachment; filename= " + sEncoding);
   
    ServletOutputStream out2 = response.getOutputStream();
    int numRead;

   // 바이트 배열b의 0번 부터 numRead번 까지 브라우저로 출력
    while((numRead = in.read(b, 0, b.length)) != -1) {
     out2.write(b, 0, numRead);
    }
    out2.flush(); 
    out2.close();
    in.close();
%>

fileList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.Map" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
   <h1>업로드 파일 리스트</h1>
   <%
      Map<String , String> map = (HashMap<String , String>)request.getAttribute("map");
      Iterator<String> keys = map.keySet().iterator();
      
      while(keys.hasNext()){
         String systemfilename = keys.next();
         String orginfilename = map.get(systemfilename);
   %>
      <p>
         <a href="file_down.jsp?file_name=<%=systemfilename %>"><%=orginfilename %></a>
      </p>
      
   <% }%>   
   
</body>
</html>
post-custom-banner

0개의 댓글