0

I've been trying to get IE11 to download a pdf file, but this seems to cause the browser to simply open a new window to render the 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;

} 
Henry
  • 7
  • 4

1 Answers1

0

Ok, I guess I'm a total noob at JSF, I seem to have gotten it working with this:

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;
}
Henry
  • 7
  • 4
  • And what are the major differences with the code in your question? And isn't there by accident an already existing 'duplicate' of this question? – Kukeltje Jun 01 '16 at 15:12
  • @Kukeltje: initial code just returned a redirect which in turn trashes the response and creates a brand new HTTP request+response on the specified URL. – BalusC Jun 01 '16 at 17:47