2012-07-03 40 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

让我朝着正确的方向前进,但仍然没有解决问题。 –

相关问题