Wednesday, January 12, 2011

Downloading Files in OAF

OAF doesn't readily expose the Controller Servlet's HttpRequest and HttpResponse objects so you need to extract it from the OAPageContext object via:

HttpServletResponse response = (HttpServletResponse) pageContext.getRenderingContext().getServletResponse();

Once you get the response object you could already manipulate its OutputStream.

     public void downloadFile(OAPageContext pageContext) {
                                       
         HttpServletResponse response = (HttpServletResponse) pageContext.getRenderingContext().getServletResponse();
        
         File fileToDownload = this.createFile();
        
         String fileType = getMimeType("txt");
         response.setContentType(fileType);
         response.setContentLength((int) fileToDownload.length());
         response.setHeader("Content-Disposition", "attachment; filename=\"" + fileToDownload.getName() + "\"");

         InputStream in = null;
         ServletOutputStream outs = null;

         try {
        
             outs = response.getOutputStream();
             in = new BufferedInputStream(new FileInputStream(fileToDownload));
             int ch;
            
             while ((ch = in.read()) != -1) {
                 outs.write(ch);
             }

         } catch (IOException e) {
        
             // TODO
             e.printStackTrace();
            
         } finally {
        
             try {
            
                 outs.flush();
                 outs.close();
                
                 if (in != null) {
                     in.close();
                 }
                
             } catch (Exception e) {
            
                 e.printStackTrace();
                
             }
            
         }
        
     }

However, manipulating the response object will flag OAF for back navigation so you might want to handle this - if you are actively checking this event.

No comments:

Post a Comment