Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private void writeOutContent(HttpServletResponse res, File content, String theFilename) {
- System.out.println("jsem ve writeOutContent");
- if (content == null) {
- System.out.println("content = null");
- return;
- }
- try {
- res.reset();
- res.setHeader("Pragma", "no-cache");
- res.setDateHeader("Expires", 0);
- res.setContentType("application/txt");
- res.setHeader("Content-Disposition", "attachment; filename=\"" + theFilename + "\"");
- res.setHeader("Content-Length", String.valueOf(content.length()));
- fastChannelCopy(Channels.newChannel(new FileInputStream(content)), Channels.newChannel(res.getOutputStream()));
- } catch (final IOException e) {
- e.printStackTrace();
- }
- System.out.println("writeOutContent ok");
- }
- //http://thomaswabner.wordpress.com/2007/10/09/fast-stream-copy-using-javanio-channels/
- private void fastChannelCopy(ReadableByteChannel src, WritableByteChannel dest) throws IOException {
- ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
- while (src.read(buffer) != -1) {
- buffer.flip();
- dest.write(buffer);
- buffer.compact();
- }
- buffer.flip();
- while (buffer.hasRemaining()) {
- dest.write(buffer);
- }
- }
- //http://ahoehma.wordpress.com/2008/03/31/jsf-file-download/
- public String downloadFile(ActionEvent event) {
- String fileName = (String) event.getComponent().getAttributes().get("fileName");
- System.out.println("budu stahovat: " + fileName);
- FacesContext facesContext = FacesContext.getCurrentInstance();
- HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
- File file = new File(Config.appPath + "export/" + fileName);
- writeOutContent(response, file, fileName);
- // Inform JSF that it doesn't need to handle response.
- // This is very important, otherwise you will get the following exception in the logs:
- // java.lang.IllegalStateException: Cannot forward after response has been committed.
- facesContext.responseComplete();
- System.out.println("end downloadFile");
- return null;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement