sitelink1  
sitelink2  
sitelink3  
sitelink4  
sitelink5  
sitelink6  

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

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

public class DownloadTest extends HttpServlet {

  /**
   *
   */
  private static final long serialVersionUID = 1L;

  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException
{
    doGet(req, res);
  }

  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException
{

    String id = req.getParameter("id");
    String pass = req.getParameter("pass");

    if (id.equals("down") && pass.equals("test")) {
      try {
        sendFile(req, res, "D:/TEST.xls");
      } catch (Exception e) {
        // Logger.err.println("File Download is failed : "+e);
      }
    } else {
      res.setContentType("text/html;charset=euc-kr");
      PrintWriter out = res.getWriter();
      out.println("<html><body><center>");
      out.println("invalid user information!!");
      out.println("</center></body></html>");
    }
  }

  /**
   * <pre>
   *      파일을 전송하는 메소드.
   * <br>
   *      파일의 절대 경로를 인자값으로 받아 파일을 전송한다.
   * <br>
   * String s = &quot;c:/jdk1.3.1/bin/javac.exe&quot;;
   * sendFile(s);
   * </pre>
   *
   * @param String
   *          path - 파일의 절대 경로
   * @return void
   * @exception java.lang.Exception
   */
  public void sendFile(HttpServletRequest request,
      HttpServletResponse response, String path) throws Exception
{
    this.sendFile(request, response, new File(path));
  }

  /**
   * <pre>
   *      파일을 전송하는 메소드
   *      &lt;b&gt;response를 reset()하기 때문에 Cookie 변경 등의 작업을 수행해서는 안된다.&lt;/b&gt;
   * </pre>
   */
  public void sendFile(HttpServletRequest request,
      HttpServletResponse response, File f) throws Exception
{

    InputStream in = null;
    OutputStream out = null;
    try {
      // File f = new File(path);
      if (!f.exists() || f.isDirectory()) {
        // Logger.err.println("File Not Exists :"+f.getAbsolutePath());
        return;
      }
      // Logger.debug.println("Download File:"+f.getAbsolutePath());
      in = new FileInputStream(f);

      // 쿠키 등의 정보를 지우므로 이전에 세팅을 해서는 안된다.
      response.reset();
      // Logger.debug.println("f.getName():"+f.getName());

      // Logger.debug.println("FileDonwload called:"+f.getName());
      String contentType = "Content-type: application/x-ms-download";

      response.setContentType(contentType);
      response.setHeader("Content-Disposition", "attachment; filename=""
          + new String(f.getName().getBytes(), "Shift_JIS") + """);
      response.setHeader("Content-Length", "" + f.length());

      out = response.getOutputStream();
      byte[] dd = new byte[4096];
      int leng = 0;
      while ((leng = in.read(dd)) > 0) {
        out.write(dd, 0, leng);
      }

    } finally {
      if (in != null)
        try {
          in.close();
        } catch (Exception e) {
        }
      if (out != null)
        try {
          out.close();
        } catch (Exception e) {
        }
    }
  }
}

번호 제목 글쓴이 날짜 조회 수
23 Polymorphism과 Method Overriding에 대한 이야기 황제낙엽 2003.05.15 330
22 자바의 특징 황제낙엽 2003.05.06 450
21 JVM (Java Virtual Machine)에 대한 몇가지 설명 황제낙엽 2003.05.06 210
20 자바설화 황제낙엽 2003.05.03 395
19 XML기반 정보 보호 기술의 대두 황제낙엽 2003.04.22 265
18 인터넷을 통한 자바 기술의 변화 황제낙엽 2003.04.07 493
17 JAVA관련 용어와 기술 황제낙엽 2003.04.05 458
16 UTF-8을 위한 문자열 인코딩처리 관련 황제낙엽 2006.10.06 881
15 Code Conventions for JavaTM Programing Language file 황제낙엽 2006.10.23 518
14 자바에서 UTF-8 개발에 관한 정리 (2) 황제낙엽 2006.10.06 543
13 자바에서 UTF-8 개발에 관한 정리 (1) 황제낙엽 2006.10.06 539
12 일본어 전각 반각 변환 예제 소스 .두번째 [1] file 황제낙엽 2007.01.11 569
11 일본어 전각 반각 변환 예제 소스 .첫번째 file 황제낙엽 2007.01.10 3371
10 환경파일 로드 클래스 구성 (XML파싱) 황제낙엽 2007.01.05 437
9 HttpURLConnection을 사용하여 웹 페이지 액세스하기 (두번째) 황제낙엽 2007.01.05 593
8 자바의 I/O 예제 [1] file 황제낙엽 2006.12.28 346
7 HttpURLConnection 클래스를 이용한 Search 황제낙엽 2006.12.28 670
6 HttpURLConnection을 사용하여 웹 페이지 액세스하기 (첫번째) 황제낙엽 2006.12.28 522
» Servlet으로 구현한 파일 다운로드(download) 페이지 황제낙엽 2006.12.27 455
4 JSP로 구현한 파일 다운로드(download) 페이지 황제낙엽 2006.12.27 2583