2014-01-19 68 views
0

我編寫了一個啓動文件下載的servlet。該文件的數據在客戶端的請求中收到。它適用於Chrome瀏覽器,但不適用於Firefox。這是什麼原因? Firefox的處理下載與其他瀏覽器不同嗎?使用Firefox下載Servlet文件

private static final int BUFFER_SIZE = 4096; 
protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
     throws ServletException, IOException { 

    String before = req.getReader().readLine(); 
    String filename = ""; 
    String content = ""; 

    if(before == null) { 
     resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No data received!"); 
     return; 
    } else {   
     String decoded = URLDecoder.decode(before, "UTF-8"); 
     { 
      int i = 0; 
      StringTokenizer tokenizer = new StringTokenizer(decoded, "\n"); 
      while (tokenizer.hasMoreTokens()) { 
       if(i == 0) { 
        filename += tokenizer.nextToken(); 
       } else { 
        content += tokenizer.nextToken(); 
       } 
       i++; 
      } 
     }   
     filename = filename.replace("hidden=", "").replace("\n", "").replace("\r", ""); 
    } 

    ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes()); 
    int fileLength = inputStream.available(); 

    ServletContext context = getServletContext(); 

    // sets MIME type for the file download 
    String mimeType = context.getMimeType(filename); 
    if (mimeType == null) {   
     mimeType = "application/octet-stream"; 
    }    

    // set content properties and header attributes for the response 
    resp.setContentType(mimeType); 
    resp.setContentLength(fileLength); 
    String headerKey = "Content-Disposition"; 
    String headerValue = String.format("attachment; filename=\"%s\"", filename); 
    resp.setHeader(headerKey, headerValue); 

    // writes the file to the client 
    OutputStream outStream = resp.getOutputStream(); 

    byte[] buffer = new byte[BUFFER_SIZE]; 
    int bytesRead = -1; 

    while ((bytesRead = inputStream.read(buffer)) != -1) { 
     outStream.write(buffer, 0, bytesRead); 
    } 

    inputStream.close(); 
    outStream.close(); 
} 
+0

請展開「不工作」部分。調試一個問題的近似是非常困難的...... –

+0

在IE瀏覽器中,Chrome瀏覽器和Safari瀏覽器的下載會顯示正確的名稱和數據,但不會顯示在Firefox中。 – Zicane

+0

這是可見的後果,但它不會幫助您調試錯誤。在這裏發佈相關的源代碼和任何其他有用的信息。 –

回答

0

如果您希望瀏覽器始終顯示下載對話框(而不是試圖打開該文件本身),試圖迫使內容類型application/octet-stream而不是設置它的基礎上的文件類型。

換句話說,嘗試更換這些線路:由

ServletContext context = getServletContext(); 

// sets MIME type for the file download 
String mimeType = context.getMimeType(filename); 
if (mimeType == null) {   
    mimeType = "application/octet-stream"; 
}    

// set content properties and header attributes for the response 
resp.setContentType(mimeType); 

這一個:

resp.setContentType("application/octet-stream"); 

我不知道你是如何觸發下載,但如果您使用的是隱藏框架,我的猜測是Firefox試圖直接在隱藏幀中打開文件,因爲它識別文件類型。