在IE11上使用jsf 1.2触发下载

时间:2016-05-31 16:56:31

标签: jsf internet-explorer-11

我一直试图让IE11下载pdf文件,但这似乎会导致浏览器只是打开一个新窗口来呈现pdf。

public void forceLoad () throws IOException {
    OutputStream out = null;

    FacesContext fc = FacesContext.getCurrentInstance();

    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse(); 
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.sendRedirect("https://math.dartmouth.edu/archive/m19w03/public_html/Section5-2.pdf");
    response.setContentType("application/octet-stream");
    //response.setContentLength(len);
    response.setHeader("Content-Disposition", "attachment; filename=\""+ "test.pdf" +"\"");
    out = response.getOutputStream();       
    out.flush();

    fc.responseComplete(); //we will need this or else JSF will attempt to render the response which would fail

    return;

} 

1 个答案:

答案 0 :(得分:0)

好吧,我想我是JSF的总菜鸟,我似乎已经开始使用它了:

public void forceLoad () throws IOException {
    int BUFFER_SIZE=4096;
    OutputStream output = null;
    InputStream input = null; 
    FacesContext context = FacesContext.getCurrentInstance();       
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();    
    URL url = new URL("https://math.dartmouth.edu/archive/m19w03/public_html/Section5-2.pdf");
    response.reset();
    response.setContentLength(getFileSize(url));
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\""+ "test.pdf" +"\"");
    try {
        disableCertificateValidation();
        input = url.openStream();
        output = new BufferedOutputStream(response.getOutputStream(), BUFFER_SIZE);
        byte[] buffer = new byte[BUFFER_SIZE]; 
        int length;  
        while ((length = input.read(buffer)) > 0) {  
            output.write(buffer, 0, length);  
        }  
    }
    catch (IOException e) {
      e.printStackTrace ();
      // Perform any other exception handling that's appropriate.
    }
    finally {
      if (input != null) { input.close();}
      if (output != null) { output.close();}
    }
    context.responseComplete(); 
    return;
}