2012-07-03 42 views
0

我正在通過Servlet生成Excel文檔。當我將響應發送回客戶端(IE8)時,彈出「打開/保存」對話框,但要求用戶在採取措施前點擊兩次選擇。這在Firefox中不會發生。我不知道爲什麼會發生這種情況。以下是創建適當流的相關代碼。IE8要求在.xls文件上打開/保存兩次

result包含Excel XML。

response.setContentType("application/vnd.ms-excel"); 
response.setHeader("Content-Disposition", "attachment;filename=TestFile.xls"); 

InputStream in = new ByteArrayInputStream(result.toString().getBytes("UTF-8")); 
ServletOutputStream out = response.getOutputStream(); 

try 
{ 
    byte[] outputByte = new byte[4096]; 

    while(in.read(outputByte, 0, 4096) != -1) 
     out.write(outputByte, 0, 4096); 
} 
finally 
{ 
    in.close(); 
    out.flush(); 
    out.close(); 
} 

編輯 我注意到,點擊選項前等待至少5秒鐘,工作得很好。它似乎只在立即點擊一個選項時詢問兩次。

+0

似乎是IE的一個bug:http://support.microsoft.com/ default.aspx?scid = http://support.microsoft.com:80/support/kb/articles/q238/5/88.asp&NoWebContent = 1,http://forums.asp.net/t/273944.aspx/ 1 – dragon66

+0

我發現了那些相同的參考文獻,但它們相當古老。我曾希望這可能是在過去的5年中得到修復的。 –

回答

1

此代碼非常適用於所有類型的文件在我的應用程序

InputStream in = blob.getBinaryStream(); 
    // Output the blob to the HttpServletResponse 

    String codedfilename = ""; 
    //this code resolves the issue with the encoding of the downloaded filename 
    String agent = request.getHeader("USER-AGENT"); 
    if (null != agent && -1 != agent.indexOf("MSIE")) 
    { 
    codedfilename = URLEncoder.encode(/*here goes the filename*/, "UTF8"); 
    response.setContentType("application/x-download"); 
    response.setHeader("Content-Disposition","attachment;filename=" + codedfilename); 
    } 
    else if (null != agent && -1 != agent.indexOf("Mozilla")) 
    { 
    response.setCharacterEncoding("UTF-8"); 
    //It does not seem to make a difference whether Q or B is chosen 
    codedfilename = MimeUtility.encodeText(rset.getString("FILE_NAME"), "UTF8", "B"); 
    response.setContentType("application/force-download"); 
    response.addHeader("Content-Disposition", "attachment; filename=\"" + codedfilename + "\""); 
    } 

    BufferedOutputStream out = 
     new BufferedOutputStream(response.getOutputStream()); 
    byte by[] = new byte[32768]; 
    int index = in.read(by, 0, 32768); 
    while (index != -1) { 
     out.write(by, 0, index); 
     index = in.read(by, 0, 32768); 
    } 
    out.flush(); 

試試吧,讓我們知道

+0

沒有什麼區別。雖然我應該提及,我已經注意到,在點擊一個選項之前等待5秒以上可以正常工作。它似乎只在立即點擊一個選項時詢問兩次。使用用戶代理的 –

+0

可能會很棘手,他們假裝對方 - http://webaim.org/blog/user-agent-string-history/。一些老的Opera在其代理中使用了MSIE。 – JIV

+0

讓我朝着正確的方向前進,但仍然沒有解決問題。 –

相關問題