因為工作上的需求,需要利用到jsp來做出檔案下載的功能

做的途中發現有一個問題,雖然檔案可以正常下載
但卻會出現Exception : getOutputStream() has already been called for this response
在網路上搜尋出來很多原因

這邊挑出其中一個比較符合我現在的狀況

在tomecat中jsp編譯成servlet之後,在函數

jspService(HttpServletRequest request, HttpServletResponse response)

的最後會執行一段程式碼
finally {
if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
}

這段Code他會使用到response.getWriter(),而這個方法又和response.getOutputStream()

牴觸到,所以就會產生這個異常。

在jsp頁面上要解決此異常有一個方法 
就是加上這兩行

   out.clear();
   out = pageContext.pushBody();

這段code詳細的意義我也還不是說很清楚,以後再上來補充報告,
或是有人知道的話也歡迎分享 !!



以下是實作程式碼

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ page import="java.io.*,java.net.*"%>

<%

    String path = "本機放置檔案路徑位置";                    //檔案主要放置目錄

    String filename = "檔案名";                   //檔案名

    filename = new String(filename.getBytes("ISO-8859-1"),"Big5");

   

    File file = new File(path+filename);

    if(file.exists()){//檢驗檔案是否存在

        try{

            response.setHeader("Content-Disposition","attachment; filename=\""  + URLEncoder.encode(filename, "UTF-8") + "\"");  

            OutputStream output = response.getOutputStream();

            InputStream in = new FileInputStream(file);

            byte[] b = new byte[2048];

            int len;

           

            while((len = in.read(b))>0){

              output.write(b,0,len);

            }

            in.close();

            output.flush();

            output.close();   //關閉串流

            out.clear();
            out = pageContext.pushBody();

        }catch(Exception ex){

            out.println("Exception : "+ex.toString());

            out.println("<br/>");

        }

    }else{

        out.println(filename+" : 此檔案不存在");

        out.println("<br/>");

    }

%>

arrow
arrow
    全站熱搜

    codingboy 發表在 痞客邦 留言(1) 人氣()