ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 파일다운로드 소스!!!! (내가 구글링하여 구현)
    JSP 2014. 5. 12. 15:53

    우선 로직들을 보기전에 간단하게  어떻게 흘러갔느지 보자!

     

     

     

    이미지 를 클릭 하면 onclick이벤트가 발생한다 --> 선택한 이미지의 값을 히든으로 ViewOk.jsp 로 보내줌

    --> 이미지 값을 request로 파라미터를 받아서 자바 로직이 컴파일됨 --> 다운로드 상자가 뜸

     

     

     

    // 페이지

    <form id="jejus" name="jejus">

    <input type= "hidden" name="foo" id="foo" value=""/> 

    <table>

    <tr>

    <td><img src="abcd" onclick = "downloader(파라미터)";

    </td>

    </tr>

    </table>

    </form>

     

    // 스크립 즉 onclick이벤트 발생되는 곳

    function downloader(파라미터) {

     

    var f = document.jejus;

     

     

    f.foo.value = "파라미터";

    f.method = "POST";

    f.action = "다운로드 기능을 처리할 페이지";

     

    }

     

     

     

    // 페이지

     OutputStream outStream = null;
     FileInputStream fileStream = null;

     
     try {
      String 파라미터= request.getParameter("파라미터");  
      String 파일경로 = "업로드하고 있는 파일 경로명";

      response.setContentType("application/x-msdownload");
      String convName1 = java.net.URLEncoder.encode(ORIGIN_FILE_NAME, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + convName1 + ";");

      String convName2 = 파라미터;
      File file = new File(파일경로  + "/" + 파라미터);

      byte[] byteStream = new byte[(int)file.length()];   // file변수길이를 int로 형변환 하여  byteStream 이라는 
                                                                                변수안에 byte로 담는다 

     fileStream = new FileInputStream(file);                   // fileStream 변수는 file을 읽어들인 것이 된다.
      int i = 0;
      int j = 0;
      while( (i=fileStream.read()) !=-1) {                       // i가 fileStream을 읽었을때 -1과 같지 않을 시 while문
                                                                                 을 돌려라 
       byteStream[j] = (byte)i;                                     // 여기서 j는 읽어들인 i값이 된다 그래서 j만큼 증가!!!
       j++;

      }
      out.clear();                                                     //새롭게 작성하는 선언 (out 객체를 초기화);
      out = pageContext.pushBody();
      outStream = response.getOutputStream();           // response.getOutputSteram()을 사용하지 않으면 파일
                                                                               이 누적하여 쌓일때 초기화 시키지 않고 물려있는 값 

       에 쌓인다. 

    outStream.write(byteStream);                               // 읽어 들인 byteStream을 outStream.write를 통해 출력

      }catch(Exception e) {
       System.out.println(e);
      }finally {
       if(fileStream != null) fileStream.close();
       if(outStream != null) outStream.close();
      }

     

    'JSP' 카테고리의 다른 글

    JSP 쿠키(Cookie) 정리 및 예시!!  (0) 2014.09.29
    JSP 액셀 다운  (0) 2014.06.09
    out 내장 객체!!  (0) 2014.06.05
    커넥션풀의 정의  (0) 2014.03.26
    JDBC  (0) 2014.03.17
Designed by Tistory.