Advertisement
Guest User

Untitled

a guest
Apr 6th, 2012
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.35 KB | None | 0 0
  1.     private void writeOutContent(HttpServletResponse res, File content, String theFilename) {
  2.         System.out.println("jsem ve writeOutContent");
  3.         if (content == null) {
  4.             System.out.println("content = null");
  5.             return;
  6.         }
  7.         try {
  8.             res.reset();
  9.             res.setHeader("Pragma", "no-cache");
  10.             res.setDateHeader("Expires", 0);
  11.             res.setContentType("application/txt");
  12.             res.setHeader("Content-Disposition", "attachment; filename=\"" + theFilename + "\"");
  13.             res.setHeader("Content-Length", String.valueOf(content.length()));
  14.             fastChannelCopy(Channels.newChannel(new FileInputStream(content)), Channels.newChannel(res.getOutputStream()));
  15.         } catch (final IOException e) {
  16.             e.printStackTrace();
  17.         }
  18.         System.out.println("writeOutContent ok");
  19.     }
  20.  
  21.     //http://thomaswabner.wordpress.com/2007/10/09/fast-stream-copy-using-javanio-channels/
  22.     private void fastChannelCopy(ReadableByteChannel src, WritableByteChannel dest) throws IOException {
  23.         ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
  24.  
  25.         while (src.read(buffer) != -1) {
  26.             buffer.flip();
  27.             dest.write(buffer);
  28.             buffer.compact();
  29.         }
  30.         buffer.flip();
  31.         while (buffer.hasRemaining()) {
  32.             dest.write(buffer);
  33.         }
  34.     }  
  35.  
  36.     //http://ahoehma.wordpress.com/2008/03/31/jsf-file-download/
  37.     public String downloadFile(ActionEvent event) {
  38.         String fileName = (String) event.getComponent().getAttributes().get("fileName");
  39.         System.out.println("budu stahovat: " + fileName);
  40.         FacesContext facesContext = FacesContext.getCurrentInstance();
  41.         HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();        
  42.  
  43.         File file = new File(Config.appPath + "export/" + fileName);
  44.  
  45.         writeOutContent(response, file, fileName);
  46.  
  47.         // Inform JSF that it doesn't need to handle response.
  48.         // This is very important, otherwise you will get the following exception in the logs:
  49.         // java.lang.IllegalStateException: Cannot forward after response has been committed.        
  50.         facesContext.responseComplete();
  51.         System.out.println("end downloadFile");
  52.         return null;    
  53.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement