We have the following requirement:
On clicking a button we need to download the file present at a particular location(we have the URL).
I have written the following in .jspx file :
<af:commandButton id="btn1" >
<af:fileDownloadActionListener contentType="text/plain; charset=utf-8" method="#{bean.getFile}"/>
</af:commandButton>
The corresponding method in bean is :
| public void getFile(FacesContext facesContext, OutputStream outputStream) { |
| HttpServletResponse response = null; |
| ServletOutputStream ouputStream = null; |
| currUrl = getFileURL("ID", 281); |
| |
| response = |
| (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); |
| try { |
| ouputStream = response.getOutputStream(); |
| ouputStream.write(this.getFileBytes(), 0,this.getFileBytes().length); |
| |
| ouputStream.flush(); |
| ouputStream.close(); |
| } catch (IOException ioe) { |
| System.out.println("IO Exception"); |
| } |
| public byte[] getFileBytes() { |
| URLConnection urlConn = null; |
| InputStream iStream = null; |
| URL url; |
| byte[] buf; |
| int byteRead; |
|
| urlConn = url.openConnection(); |
| iStream = urlConn.getInputStream(); |
| buf = new byte[5000000]; |
| byteRead = iStream.read(buf); |
| if (byteRead > 0) { |
| System.out.println("Downloaded Successfully."); |
| } |
| return buf; |
| } |
| } catch (FileNotFoundException fnfe) { |
| System.out.println("File not found Exception"); |
| fnfe.printStackTrace(); |
| } catch (Exception e) { |
| System.out.println("Exception:" + e.getMessage()); |
| e.printStackTrace(); |
| } finally { |
| try { |
| iStream.close(); |
| } catch (IOException e) { |
| System.out.println("IO Exception"); |
| e.printStackTrace(); |
| } |
| } |
| System.out.println("File"); |
| return null; |
| } |
The file is opening in same window but in some encrypted format. My requirement is to :
1. Have a pop (as in Mozilla or IE) which asks if I want to save the file or open.
2. Depending on that the file should be opened in pdf format and not in browser same window neither in browser tab.