Re: Download file after dialog
I think partialSubmit must be false on the parent component (the one that contains the listener) -M On Nov 9, 2007 1:15 PM, Oscar Reitsma [EMAIL PROTECTED] wrote: Good Day, I am having an issue downloading a file depending on parameters inputted on a dialog. Perhaps someone could point me in the right direction Basically required functionality is as follows: - A user clicks on a link to generate a report. - A dialog pops up where the user can input parameters for the report. - The user clicks the OK button - The report is generated, and sent to the user as a file download. Versions: MyFaces v1.1.5 Trinidad v1.0.3 Jetty 6.1.5 Firefox: 2.0.0.9 / IE 6.0 I've tried a few ways of doing this. 1. Attempt the generation and download in the dialogs return method. This causes an invalid PPR response (as seen using FireBug) public void handleDialogReturn(ReturnEvent evt) { FacesContext context = FacesContext.getCurrentInstance(); HttpServletResponse response = ( HttpServletResponse ) context.getExternalContext ().getResponse(); OutputStream out = null; InputStream in = null; try { in = getService().generateReport( selectedReport, getSelectedMonth(), getSelectedYear(), getReportType()); if (in != null) { response.setContentType(getReportContentType()); // i.e. application/vnd.ms-excel response.setHeader(Content-Disposition, attachment;filename=\ + selectedReport.getFilename() ); out = response.getOutputStream(); int read = -1; byte[] buffer = new byte[1024]; while ((read = in.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, read); } out.flush(); } } catch (IOException ex) { } finally { try { out.close(); } catch (Exception ex) {} try { in.close(); } catch (Exception ex) {} } context.responseComplete(); } 2. Try to do the same thing in the actionListener method of the dialog's commandButton. The download here works, however, when calling the returnFromDialog method, I get the following exception and the dialog remains in view: Caused by: java.lang.IllegalStateException: STREAM at org.mortbay.jetty.Response .getWriter(Response.java:583) at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:122) at org.apache.myfaces.trinidadinternal.renderkit.core.CoreRenderKit._getHtmlWriter(CoreRenderKit.java:744) at org.apache.myfaces.trinidadinternal.renderkit.core.CoreRenderKit.returnFromDialog (CoreRenderKit.java:282) at org.apache.myfaces.trinidadinternal.context.DialogServiceImpl.returnFromDialog(DialogServiceImpl.java:173) at org.apache.myfaces.trinidadinternal.context.RequestContextImpl.returnFromDialog (RequestContextImpl.java:122) Any comments/suggestions would be highly appreciated, thanks, Oscar -- Matthias Wessendorf further stuff: blog: http://matthiaswessendorf.wordpress.com/ mail: matzew-at-apache-dot-org
Re: Download file after dialog
Hi Matthias, Thanks for your response. That is one of the puzzling things. neither the commandLink launching the dialog, nor the commandButton that causes the returnFromDialog method to be called uses partial submit. As for the exception resulting from the 2nd process outlined in my original mail, I found this link: http://jira.codehaus.org/browse/JETTY-231 If I understand the message from Greg Wilkins on that page correctly, then according to the JSF spec binary file download cannot take place in the same response as the returnFromDialog instruction, if the latter causes a call to getWriter on the response Stream. Am I interpretting that correctly? Once again, thanks for the support, Kind Regards, Oscar Reitsma On Nov 9, 2007 2:46 PM, Matthias Wessendorf [EMAIL PROTECTED] wrote: I think partialSubmit must be false on the parent component (the one that contains the listener) -M On Nov 9, 2007 1:15 PM, Oscar Reitsma [EMAIL PROTECTED] wrote: Good Day, I am having an issue downloading a file depending on parameters inputted on a dialog. Perhaps someone could point me in the right direction Basically required functionality is as follows: - A user clicks on a link to generate a report. - A dialog pops up where the user can input parameters for the report. - The user clicks the OK button - The report is generated, and sent to the user as a file download. Versions: MyFaces v1.1.5 Trinidad v1.0.3 Jetty 6.1.5 Firefox: 2.0.0.9 / IE 6.0 I've tried a few ways of doing this. 1. Attempt the generation and download in the dialogs return method. This causes an invalid PPR response (as seen using FireBug) public void handleDialogReturn(ReturnEvent evt) { FacesContext context = FacesContext.getCurrentInstance(); HttpServletResponse response = ( HttpServletResponse ) context.getExternalContext().getResponse(); OutputStream out = null; InputStream in = null; try { in = getService().generateReport( selectedReport, getSelectedMonth(), getSelectedYear(), getReportType()); if (in != null) { response.setContentType(getReportContentType()); // i.e. application/vnd.ms-excel response.setHeader(Content-Disposition, attachment;filename=\ + selectedReport.getFilename() ); out = response.getOutputStream(); int read = -1; byte[] buffer = new byte[1024]; while ((read = in.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, read); } out.flush(); } } catch (IOException ex) { } finally { try { out.close(); } catch (Exception ex) {} try { in.close(); } catch (Exception ex) {} } context.responseComplete(); } 2. Try to do the same thing in the actionListener method of the dialog's commandButton. The download here works, however, when calling the returnFromDialog method, I get the following exception and the dialog remains in view: Caused by: java.lang.IllegalStateException: STREAM at org.mortbay.jetty.Response .getWriter(Response.java:583) at javax.servlet.ServletResponseWrapper.getWriter( ServletResponseWrapper.java:122) at org.apache.myfaces.trinidadinternal.renderkit.core.CoreRenderKit._getHtmlWriter (CoreRenderKit.java:744) at org.apache.myfaces.trinidadinternal.renderkit.core.CoreRenderKit.returnFromDialog (CoreRenderKit.java:282) at org.apache.myfaces.trinidadinternal.context.DialogServiceImpl.returnFromDialog (DialogServiceImpl.java:173) at org.apache.myfaces.trinidadinternal.context.RequestContextImpl.returnFromDialog (RequestContextImpl.java:122) Any comments/suggestions would be highly appreciated, thanks, Oscar -- Matthias Wessendorf further stuff: blog: http://matthiaswessendorf.wordpress.com/ mail: matzew-at-apache-dot-org
Re: Download file after dialog
sounds like that this happens. download inside the dialog possible ? On Nov 9, 2007 2:30 PM, Oscar Reitsma [EMAIL PROTECTED] wrote: Hi Matthias, Thanks for your response. That is one of the puzzling things. neither the commandLink launching the dialog, nor the commandButton that causes the returnFromDialog method to be called uses partial submit. As for the exception resulting from the 2nd process outlined in my original mail, I found this link: http://jira.codehaus.org/browse/JETTY-231 If I understand the message from Greg Wilkins on that page correctly, then according to the JSF spec binary file download cannot take place in the same response as the returnFromDialog instruction, if the latter causes a call to getWriter on the response Stream. Am I interpretting that correctly? Once again, thanks for the support, Kind Regards, Oscar Reitsma On Nov 9, 2007 2:46 PM, Matthias Wessendorf [EMAIL PROTECTED] wrote: I think partialSubmit must be false on the parent component (the one that contains the listener) -M On Nov 9, 2007 1:15 PM, Oscar Reitsma [EMAIL PROTECTED] wrote: Good Day, I am having an issue downloading a file depending on parameters inputted on a dialog. Perhaps someone could point me in the right direction Basically required functionality is as follows: - A user clicks on a link to generate a report. - A dialog pops up where the user can input parameters for the report. - The user clicks the OK button - The report is generated, and sent to the user as a file download. Versions: MyFaces v1.1.5 Trinidad v1.0.3 Jetty 6.1.5 Firefox: 2.0.0.9 / IE 6.0 I've tried a few ways of doing this. 1. Attempt the generation and download in the dialogs return method. This causes an invalid PPR response (as seen using FireBug) public void handleDialogReturn(ReturnEvent evt) { FacesContext context = FacesContext.getCurrentInstance(); HttpServletResponse response = ( HttpServletResponse ) context.getExternalContext ().getResponse(); OutputStream out = null; InputStream in = null; try { in = getService().generateReport( selectedReport, getSelectedMonth(), getSelectedYear(), getReportType()); if (in != null) { response.setContentType(getReportContentType()); // i.e. application/vnd.ms-excel response.setHeader (Content-Disposition, attachment;filename=\ + selectedReport.getFilename() ); out = response.getOutputStream(); int read = -1; byte[] buffer = new byte[1024]; while ((read = in.read(buffer, 0, buffer.length)) != -1) { out.write (buffer, 0, read); } out.flush(); } } catch (IOException ex) { } finally { try { out.close(); } catch (Exception ex) {} try { in.close(); } catch (Exception ex) {} } context.responseComplete(); } 2. Try to do the same thing in the actionListener method of the dialog's commandButton. The download here works, however, when calling the returnFromDialog method, I get the following exception and the dialog remains in view: Caused by: java.lang.IllegalStateException : STREAM at org.mortbay.jetty.Response .getWriter(Response.java:583) at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:122) at org.apache.myfaces.trinidadinternal.renderkit.core.CoreRenderKit._getHtmlWriter (CoreRenderKit.java:744) at org.apache.myfaces.trinidadinternal.renderkit.core.CoreRenderKit.returnFromDialog (CoreRenderKit.java:282) at org.apache.myfaces.trinidadinternal.context.DialogServiceImpl.returnFromDialog (DialogServiceImpl.java:173) at org.apache.myfaces.trinidadinternal.context.RequestContextImpl.returnFromDialog (RequestContextImpl.java:122) Any comments/suggestions would be highly appreciated, thanks, Oscar -- Matthias Wessendorf further stuff: blog: http://matthiaswessendorf.wordpress.com/ mail: matzew-at-apache-dot-org -- Matthias Wessendorf further stuff: blog: http://matthiaswessendorf.wordpress.com/ mail: matzew-at-apache-dot-org
Re: Download file after dialog
Download works perfectly inside the dialog. I thought a workaround would be to simply navigate the dialog to a confirmation page which the user could then dismiss, however, it seems that the dialog refuses to navigate after the download. (Without any download action, the navigation works perfectly) I have also tried using the tr:fileDownloadListener, but the effect is the same. Any other points of advice would be appreciated. Kind Regards, Oscar On Nov 9, 2007 4:17 PM, Matthias Wessendorf [EMAIL PROTECTED] wrote: sounds like that this happens. download inside the dialog possible ? On Nov 9, 2007 2:30 PM, Oscar Reitsma [EMAIL PROTECTED] wrote: Hi Matthias, Thanks for your response. That is one of the puzzling things. neither the commandLink launching the dialog, nor the commandButton that causes the returnFromDialog method to be called uses partial submit. As for the exception resulting from the 2nd process outlined in my original mail, I found this link: http://jira.codehaus.org/browse/JETTY-231 If I understand the message from Greg Wilkins on that page correctly, then according to the JSF spec binary file download cannot take place in the same response as the returnFromDialog instruction, if the latter causes a call to getWriter on the response Stream. Am I interpretting that correctly? Once again, thanks for the support, Kind Regards, Oscar Reitsma On Nov 9, 2007 2:46 PM, Matthias Wessendorf [EMAIL PROTECTED] wrote: I think partialSubmit must be false on the parent component (the one that contains the listener) -M On Nov 9, 2007 1:15 PM, Oscar Reitsma [EMAIL PROTECTED] wrote: Good Day, I am having an issue downloading a file depending on parameters inputted on a dialog. Perhaps someone could point me in the right direction Basically required functionality is as follows: - A user clicks on a link to generate a report. - A dialog pops up where the user can input parameters for the report. - The user clicks the OK button - The report is generated, and sent to the user as a file download. Versions: MyFaces v1.1.5 Trinidad v1.0.3 Jetty 6.1.5 Firefox: 2.0.0.9 / IE 6.0 I've tried a few ways of doing this. 1. Attempt the generation and download in the dialogs return method. This causes an invalid PPR response (as seen using FireBug) public void handleDialogReturn(ReturnEvent evt) { FacesContext context = FacesContext.getCurrentInstance(); HttpServletResponse response = ( HttpServletResponse ) context.getExternalContext ().getResponse(); OutputStream out = null; InputStream in = null; try { in = getService().generateReport( selectedReport, getSelectedMonth(), getSelectedYear(), getReportType()); if (in != null) { response.setContentType(getReportContentType()); // i.e. application/vnd.ms-excel response.setHeader (Content-Disposition, attachment;filename=\ + selectedReport.getFilename() ); out = response.getOutputStream(); int read = -1; byte[] buffer = new byte[1024]; while ((read = in.read(buffer, 0, buffer.length)) != -1) { out.write (buffer, 0, read); } out.flush(); } } catch (IOException ex) { } finally { try { out.close(); } catch (Exception ex) {} try { in.close(); } catch (Exception ex) {} } context.responseComplete(); } 2. Try to do the same thing in the actionListener method of the dialog's commandButton. The download here works, however, when calling the returnFromDialog method, I get the following exception and the dialog remains in view: Caused by: java.lang.IllegalStateException : STREAM at org.mortbay.jetty.Response .getWriter(Response.java:583) at javax.servlet.ServletResponseWrapper.getWriter( ServletResponseWrapper.java:122) at org.apache.myfaces.trinidadinternal.renderkit.core.CoreRenderKit._getHtmlWriter (CoreRenderKit.java:744) at org.apache.myfaces.trinidadinternal.renderkit.core.CoreRenderKit.returnFromDialog (CoreRenderKit.java:282) at org.apache.myfaces.trinidadinternal.context.DialogServiceImpl.returnFromDialog (DialogServiceImpl.java:173) at
Re: Download File
Trinidad has an actionlistener for that. If you aren't using trinidad, you still can take a look at the code and use its logic. -Matthias On 9/13/07, Wolfgang [EMAIL PROTECTED] wrote: Hi, is there any kind of a jsf component with which I can download files? I need just a simple download-button on my webpage. Cheers! -- Matthias Wessendorf further stuff: blog: http://matthiaswessendorf.wordpress.com/ mail: matzew-at-apache-dot-org
Re: Download File
Which Trinidad component should that be?? Can I also use the upload file component for downloading? Trinidad has an actionlistener for that. If you aren't using trinidad, you still can take a look at the code and use its logic. -Matthias On 9/13/07, Wolfgang [EMAIL PROTECTED] wrote: Hi, is there any kind of a jsf component with which I can download files? I need just a simple download-button on my webpage. Cheers!
Re: Download File
http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_fileDownloadActionListener.html Regards, Volker 2007/9/13, Wolfgang [EMAIL PROTECTED]: Which Trinidad component should that be?? Can I also use the upload file component for downloading? Trinidad has an actionlistener for that. If you aren't using trinidad, you still can take a look at the code and use its logic. -Matthias On 9/13/07, Wolfgang [EMAIL PROTECTED] wrote: Hi, is there any kind of a jsf component with which I can download files? I need just a simple download-button on my webpage. Cheers!
Re: Download File
On 9/13/07, Wolfgang [EMAIL PROTECTED] wrote: Which Trinidad component should that be?? no component; an actionListener. See the doc: http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_fileDownloadActionListener.html source is here: http://svn.apache.org/viewvc/myfaces/trinidad/trunk/trinidad/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/taglib/listener/FileDownloadActionListener.java?revision=548532view=markup Can I also use the upload file component for downloading? no. greetings, matthias Trinidad has an actionlistener for that. If you aren't using trinidad, you still can take a look at the code and use its logic. -Matthias On 9/13/07, Wolfgang [EMAIL PROTECTED] wrote: Hi, is there any kind of a jsf component with which I can download files? I need just a simple download-button on my webpage. Cheers! -- Matthias Wessendorf further stuff: blog: http://matthiaswessendorf.wordpress.com/ mail: matzew-at-apache-dot-org
Re: Download File
You can also do this with plain jsf in a action method. Search for this method getInstrumentsBySecCodePattern on this page : http://wiki.apache.org/myfaces/Exporting_DataTable_To_MS-Excel That method could easily be changed into a normal action method. Seem to remeber there was a page in the wiki with howto-download information but couldn't find it :) Cheers, Mike On 13/09/2007, Matthias Wessendorf [EMAIL PROTECTED] wrote: On 9/13/07, Wolfgang [EMAIL PROTECTED] wrote: Which Trinidad component should that be?? no component; an actionListener. See the doc: http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_fileDownloadActionListener.html source is here: http://svn.apache.org/viewvc/myfaces/trinidad/trunk/trinidad/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/taglib/listener/FileDownloadActionListener.java?revision=548532view=markup Can I also use the upload file component for downloading? no. greetings, matthias Trinidad has an actionlistener for that. If you aren't using trinidad, you still can take a look at the code and use its logic. -Matthias On 9/13/07, Wolfgang [EMAIL PROTECTED] wrote: Hi, is there any kind of a jsf component with which I can download files? I need just a simple download-button on my webpage. Cheers! -- Matthias Wessendorf further stuff: blog: http://matthiaswessendorf.wordpress.com/ mail: matzew-at-apache-dot-org
Re: Download File
Sorry wrong method name, should be exportHtmlTableToExcel, copy pasting is difficult ;) On 13/09/2007, Mikael Andersson [EMAIL PROTECTED] wrote: You can also do this with plain jsf in a action method. Search for this method getInstrumentsBySecCodePattern on this page : http://wiki.apache.org/myfaces/Exporting_DataTable_To_MS-Excel That method could easily be changed into a normal action method. Seem to remeber there was a page in the wiki with howto-download information but couldn't find it :) Cheers, Mike On 13/09/2007, Matthias Wessendorf [EMAIL PROTECTED] wrote: On 9/13/07, Wolfgang [EMAIL PROTECTED] wrote: Which Trinidad component should that be?? no component; an actionListener. See the doc: http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_fileDownloadActionListener.html source is here: http://svn.apache.org/viewvc/myfaces/trinidad/trunk/trinidad/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/taglib/listener/FileDownloadActionListener.java?revision=548532view=markup Can I also use the upload file component for downloading? no. greetings, matthias Trinidad has an actionlistener for that. If you aren't using trinidad, you still can take a look at the code and use its logic. -Matthias On 9/13/07, Wolfgang [EMAIL PROTECTED] wrote: Hi, is there any kind of a jsf component with which I can download files? I need just a simple download-button on my webpage. Cheers! -- Matthias Wessendorf further stuff: blog: http://matthiaswessendorf.wordpress.com/ mail: matzew-at-apache-dot-org
Re: Download file from server to local
Xaio, Yes, this won't work in a portal environment. Your file needs to be a resource that you retrieve and, as such, the url to your file needs to be encoded as a resource url. Nuisances aside, consider a normal portal usecase where an action will cause all portlets on the screen to resubmit. This means that the Portal needs to return all of it's data, including data for itself and all the other portlets, to the screen at the same time. The Portal, therefore, has to force the content type to be something compatible with itself and all portlets. My suggestion would be to create a servlet which deletes the file for you and sends the resource back with the correct content type. You would then encode the url to this servlet as a resource url and use something like a goLink to access it. Also note that some renderkits will do the encoding for you, so you should make sure that you use the correct component to reference this servlet. I know the Trinidad goLink encodes url's as a resource url. I'm not sure about the other renderkits. Scott xiao wang wrote: Hi there, I am writing JSF portlet using myFaces. The JSF portlet will download a file to local from server and the file in the server side will be deleted after downloaded. The code works fine as a web application. But it can not work properly as portlet. In a jsp page, a button is displayed to invoke the downloadFile method. h:commandButton value=downLoad action=#{myFile.downloadFile} /. When running my JSF code as web application, to click the downLoad button, a window will popup to display open or save the file. But if running as JSF portlet, when click the downLoad button, no window pops up. But the file in the server side does be deleted after the button is clicked. any idea? Thanks a lot in advance. Below is the method to download file from server: public void downloadFile(){ javax.faces.context.FacesContext conText = javax.faces.context.FacesContext.getCurrentInstance(); javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse )conText.getExternalContext().getResponse(); String path = System.getProperty(java.io.tmpdir); filename = test.ppt; File file = null; try { String _fileString = path + File.separator + filename; file = new File(_fileString); java.io.FileInputStream fis = new java.io.FileInputStream(file); String contenttype = application/octet-stream; response.setContentType(contenttype); response.setHeader(Content-Disposition, attachment; filename= + filename + ;); javax.servlet.ServletOutputStream out = response.getOutputStream(); int c = 0; while ((c=fis.read())!=-1) { out.write(c); } out.flush(); out.close(); file.delete(); } catch (Exception e) { if (file!=null file.exists()) { file.delete(); System.out.println([srb] file deleted on web server); } return; } conText.getApplication().getStateManager().saveSerializedView(conText); conText.responseComplete(); }
Re: download file breaks lifecycle
Hello, I posted a question previously relating to this that unfortunately has not had any replies - I'm hoping to get this resolved I have the same problem whereby the file's downloaded then any subsequent action on the page causes the file to re-download. I have added the saveSerializedView method but to no avail. The action is triggered via a command link - now if I replace the command link with a command button this issue goes away; but I really don't want to use a button if I can help it! Can anybody help me with this please? Many thanks in advance, Carl Jeff Bischoff wrote: David, Thanks for the hint. Though I didn't ask the question, I have seen this behavior on one or two of my pages. Now I'll have a chance to fix it perhaps. Hmm... I went to the link your code points to, but there was really no mention of *why* this solution works. Do you know who originally figured this out or why it is necessary? I assume it's because we are skipping some necessary lifecycle phase when we write to the out and then call responseComplete? Regards, Jeff Bischoff Kenneth L Kurz Associates, Inc. David Chandler wrote: Simply add these two lines of code before the call to responseComplete(): // Save serialized view or else after clicking on the export button, user will have to click TWICE to invoke another action // See http://swforum.sun.com/jive/thread.jspa?threadID=63566 StateManager stateManager = (StateManager) facesContext .getApplication().getStateManager(); stateManager.saveSerializedView(facesContext); /dmc On 12/29/06, ::SammyRulez:: [EMAIL PROTECTED] wrote: Hello and happy new year Im' using this action method to generate dynamicaly pdf file and send them to the browser public String generaContratto(){ FacesContext facesContext = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); response.setContentType(application/pdf); String fileName = blabla.pdf; response.setHeader(Content-disposition, attachment; filename=\ + fileName + \); try { ServletOutputStream out; out = response.getOutputStream(); ProxyDaoFactory daoFactory = new ProxyDaoFactory(); DocumentBuilder builder = new DocumentBuilderWrapper(daoFactory, facesContext.getExternalContext().getInitParameter(fileValut)); builder.write(offerta,out); } catch (Exception e) { ... return ERROR } facesContext.responseComplete(); return OK; } Everithing works fine: the pdf is generated, downloaded etc. But if I trigger some other action on the same view it just render the page again.. I think it does render response phase. Model is not updated. It act as if navigation (the ugly back button!) button where used. Any ideas? -- ::SammyRulez:: http://www.kyub.com/blog/ - La programmazione è per un terzo interpretazione e per due terzi ispirazione. E per un terzo mistificazione -- View this message in context: http://www.nabble.com/download-file-breaks-lifecycle-tf2893828.html#a8447914 Sent from the MyFaces - Users mailing list archive at Nabble.com.
Re: Download file component by jsf?
Chen, Wei schrieb: Hi, JSF has the uploadFile component and can use this to upload a file onto the server. But how can I download a file? Or what I want is: if I click a hyber-link, a download file dialog will be shown and the file will be saved in local. How can I do that with jsf? Regards Wei Hmm i think sth like this is not included in jsf, what i do to archieve the same. You can either 1) - make a hyperlink to the file (common case) 2) - point a link to a servlet that will return the file as stream
Re: Download file component by jsf?
On 1/5/07, Holger Prause [EMAIL PROTECTED] wrote: Chen, Wei schrieb: Hi, JSF has the uploadFile component and can use this to upload a file onto the server. But how can I download a file? Or what I want is: if I click a hyber-link, a download file dialog will be shown and the file will be saved in local. How can I do that with jsf? Regards Wei Hmm i think sth like this is not included in jsf, what i do to archieve the same. You can either 1) - make a hyperlink to the file (common case) 2) - point a link to a servlet that will return the file as stream To expand upon this just a little bit ... What a browser does when presented with a response has nothing to do with what technology you used to produce the response (JSF or Struts or PHP or ASP.Net or whatever), and everything to do with the content type (and/or the file extension) of the response URL. So, when you create a hyperlink to, say report.pdf (or use a content type of application/pdf), the browser consults its mappings for how to handle this content type (there are defaults built in for the common types, but the user can also define their own), and decides what to do. So, what you should really be doing is pointing at a link that sends the data you want, with an appropriate content type and filename suffix. If the file isn't of type text/html (which would be displayed directly in the browser window), then the user gets to choose what really happens. If you really want to trigger the save data dialog, your best bet is to set the content type to something like application/data, and/or use an extension on the URL that the browser will not map to some predefined handler. Craig
Re: download file breaks lifecycle
Simply add these two lines of code before the call to responseComplete(): // Save serialized view or else after clicking on the export button, user will have to click TWICE to invoke another action // See http://swforum.sun.com/jive/thread.jspa?threadID=63566 StateManager stateManager = (StateManager) facesContext .getApplication().getStateManager(); stateManager.saveSerializedView(facesContext); /dmc On 12/29/06, ::SammyRulez:: [EMAIL PROTECTED] wrote: Hello and happy new year Im' using this action method to generate dynamicaly pdf file and send them to the browser public String generaContratto(){ FacesContext facesContext = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); response.setContentType(application/pdf); String fileName = blabla.pdf; response.setHeader(Content-disposition, attachment; filename=\ + fileName + \); try { ServletOutputStream out; out = response.getOutputStream(); ProxyDaoFactory daoFactory = new ProxyDaoFactory(); DocumentBuilder builder = new DocumentBuilderWrapper(daoFactory, facesContext.getExternalContext().getInitParameter(fileValut)); builder.write(offerta,out); } catch (Exception e) { ... return ERROR } facesContext.responseComplete(); return OK; } Everithing works fine: the pdf is generated, downloaded etc. But if I trigger some other action on the same view it just render the page again.. I think it does render response phase. Model is not updated. It act as if navigation (the ugly back button!) button where used. Any ideas? -- ::SammyRulez:: http://www.kyub.com/blog/ - La programmazione è per un terzo interpretazione e per due terzi ispirazione. E per un terzo mistificazione -- David Chandler Development Coach learnjsf.com
Re: download file breaks lifecycle
David, Thanks for the hint. Though I didn't ask the question, I have seen this behavior on one or two of my pages. Now I'll have a chance to fix it perhaps. Hmm... I went to the link your code points to, but there was really no mention of *why* this solution works. Do you know who originally figured this out or why it is necessary? I assume it's because we are skipping some necessary lifecycle phase when we write to the out and then call responseComplete? Regards, Jeff Bischoff Kenneth L Kurz Associates, Inc. David Chandler wrote: Simply add these two lines of code before the call to responseComplete(): // Save serialized view or else after clicking on the export button, user will have to click TWICE to invoke another action // See http://swforum.sun.com/jive/thread.jspa?threadID=63566 StateManager stateManager = (StateManager) facesContext .getApplication().getStateManager(); stateManager.saveSerializedView(facesContext); /dmc On 12/29/06, ::SammyRulez:: [EMAIL PROTECTED] wrote: Hello and happy new year Im' using this action method to generate dynamicaly pdf file and send them to the browser public String generaContratto(){ FacesContext facesContext = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); response.setContentType(application/pdf); String fileName = blabla.pdf; response.setHeader(Content-disposition, attachment; filename=\ + fileName + \); try { ServletOutputStream out; out = response.getOutputStream(); ProxyDaoFactory daoFactory = new ProxyDaoFactory(); DocumentBuilder builder = new DocumentBuilderWrapper(daoFactory, facesContext.getExternalContext().getInitParameter(fileValut)); builder.write(offerta,out); } catch (Exception e) { ... return ERROR } facesContext.responseComplete(); return OK; } Everithing works fine: the pdf is generated, downloaded etc. But if I trigger some other action on the same view it just render the page again.. I think it does render response phase. Model is not updated. It act as if navigation (the ugly back button!) button where used. Any ideas? -- ::SammyRulez:: http://www.kyub.com/blog/ - La programmazione è per un terzo interpretazione e per due terzi ispirazione. E per un terzo mistificazione
Re: Download file q
Keith, Thanks for this tip. I haven't experienced this behavior (svn Myfaces, facelets 1.0, firefox 1.0.7, client-side state saving) even though I don't have this line of code. Can you explain that the problem is and why saveSerializedView() solves it? I'd like to know if I'm going to be hit by it at some future point. Also, some of the other myfaces committers were talking about creating a download component, so it'd be good to know when we need to include this code. On 12/21/05, Keith Lynch [EMAIL PROTECTED] wrote: With the code above you'll run into a problem whereby on the page a click seems to be ignored after the download. Put this before responseComplete to fix things up. context.getApplication().getStateManager().saveSerializedView(context); On 12/19/05, Mike Kienenberger [EMAIL PROTECTED] wrote: On 12/19/05, Anu Padki [EMAIL PROTECTED] wrote: Is it not possible to download a file using action method? Do we have to write a servlet? Nope. Here's how I do it. public String downloadContentData() { Content selectedContent = (Content)this.announcementContentDataList.getRowData(); FacesContext facesContext = FacesContext.getCurrentInstance (); try { OutputStream responseStream = ((HttpServletResponse)facesContext.getExternalContext().getResponse()).getOutputStream(); HttpServletResponse response = (HttpServletResponse)facesContext.getExternalContext().getResponse(); response.setContentType(selectedContent.getContentType()); response.setHeader(Content-Disposition,attachment;filename=\ + selectedContent.getContentId() + \); response.setContentLength(selectedContent.getContentData().getData().length); responseStream.write(selectedContent.getContentData ().getData()); response.flushBuffer(); } catch (IOException exception) { // TODO Auto-generated catch block exception.printStackTrace(); } facesContext.responseComplete(); return downloadContentData; }
Re: Download file q
With the code above you'll run into a problem whereby on the page a click seems to be ignored after the download.Put this before responseComplete to fix things up.context.getApplication().getStateManager().saveSerializedView(context); On 12/19/05, Mike Kienenberger [EMAIL PROTECTED] wrote: On 12/19/05, Anu Padki [EMAIL PROTECTED] wrote: Is it not possible to download a file using action method? Do we have to write a servlet?Nope.Here's how I do it. public String downloadContentData(){Content selectedContent =(Content)this.announcementContentDataList.getRowData();FacesContext facesContext = FacesContext.getCurrentInstance ();try{OutputStream responseStream =((HttpServletResponse)facesContext.getExternalContext().getResponse()).getOutputStream();HttpServletResponse response = (HttpServletResponse)facesContext.getExternalContext().getResponse();response.setContentType(selectedContent.getContentType());response.setHeader(Content-Disposition,attachment;filename=\ + selectedContent.getContentId() + \);response.setContentLength(selectedContent.getContentData().getData().length);responseStream.write(selectedContent.getContentData ().getData()); response.flushBuffer();}catch (IOException exception){// TODO Auto-generated catch blockexception.printStackTrace();} facesContext.responseComplete();return downloadContentData;}
Re: Download file q
Yes is possible. HttpServletResponse response = (HttpServletResponse) facesContext .getExternalContext().getResponse(); ServletOutputStream out; try { out = response.getOutputStream(); if (currentItem.getDocument() != null) { log.info("Attached document exists for " + currentItem); response.setContentType("message/rfc822"); response.setHeader("Content-disposition", "inline;filename=file.mht"); out.write(currentItem.getDocument()); } else { log.info("Not existing attached document. Using default text. " + ...); response.setContentType("text/html"); out.write(("No document for " + currentItem.getTitle()) .getBytes()); } out.flush(); } catch (Exception e) { log.debug(".. ", e); } facesContext.responseComplete(); Regards Marius Anu Padki wrote: Is it not possible to download a file using action method? Do we have to write a servlet? Thanks. - Anu begin:vcard fn:Oancea Marius n:Marius;Oancea org:Hermann Oberth Faculty of Engineering, Lucian Blaga University of Sibiu;Department of Computer Science adr:;;4 Emil Cioran Str.;Sibiu;Sibiu;550025;Roumania email;internet:[EMAIL PROTECTED] title:Asist. Ing. tel;home:+40 369 401740 tel;cell:+40 742 207963 url:http://www.csac.ulbsibiu.ro version:2.1 end:vcard
Re: Download file q
On 12/19/05, Anu Padki [EMAIL PROTECTED] wrote: Is it not possible to download a file using action method? Do we have to write a servlet? Nope. Here's how I do it. public String downloadContentData() { Content selectedContent = (Content)this.announcementContentDataList.getRowData(); FacesContext facesContext = FacesContext.getCurrentInstance(); try { OutputStream responseStream = ((HttpServletResponse)facesContext.getExternalContext().getResponse()).getOutputStream(); HttpServletResponse response = (HttpServletResponse)facesContext.getExternalContext().getResponse(); response.setContentType(selectedContent.getContentType()); response.setHeader(Content-Disposition,attachment;filename=\ + selectedContent.getContentId() + \); response.setContentLength(selectedContent.getContentData().getData().length); responseStream.write(selectedContent.getContentData().getData()); response.flushBuffer(); } catch (IOException exception) { // TODO Auto-generated catch block exception.printStackTrace(); } facesContext.responseComplete(); return downloadContentData; }
Re: Download file from browser problem - two clicks
I had this problem a few days ago w/ 1.0.9 but I can't reproduce it. Original message Date: Sun, 04 Sep 2005 01:38:12 +0200 From: Jaroslav Rychna [EMAIL PROTECTED] Subject: Re: Download file from browser problem - two clicks To: users@myfaces.apache.org Hi, did you solve the problem with double clicks? I'm facing the same. First click does nothing and the second downloads the file. My code in jsp is: x:commandLink actionListener=#{rezervace.toPdf} title=# {bundle.f_tisk} immediate=true / thanks, jarin Aris Bartee napsal(a): I'm sorry. My reply was from memory. I used the action listener tag inside of a command link. Here's the snippet: h:commandLink value=#{file} action=downloadfile h:outputText value=#{file} jsf:converter converterId=FileNameConverter/ /h:outputText jsf:actionListener type=pamcep.jsf.event.RetrieveFile/ /h:commandLink The version I used this with is 1.03. --- [EMAIL PROTECTED] wrote: Thanks for responding Aris, I have implemented what you suggested and am still getting the same problem (note I am using MyFaces 1.0.7). Have I implemented it below the way you have it? I put an actionListener on my commandLink and use an ActionEvent method to capture the line of the dataTable that they selected. I then call writeFileToBrowser and at the end specify FacesContext.getCurrentInstance().responseComplete(). Do you see where I may have something wrong? h:commandLink actionListener=#{DocumentCtl.downloadPDF} immediate=true h:outputText value=view styleClass=copy/ /h:commandLink public void downloadPDF(ActionEvent event) { Document doc = (Document) UIHelper.getReqMapObj(document); String file = Sysctl.getRecord().getLowresfolder() + doc.getGuid() + .pdf; writeFileToBrowser(file, doc.getName() + .pdf, doc.getUploadtype()); } private void writeFileToBrowser(String fileSource, String downloadName, String contentType) { if (!FacesContext.getCurrentInstance().getResponseComplete() FileControl.exists(fileSource)) { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); response.setContentType(contentType); response.setHeader(Content-Disposition, attachment;filename=\ + downloadName + \); try { ServletOutputStream out = response.getOutputStream(); BufferedInputStream bufferedinputstream = new BufferedInputStream( new FileInputStream(fileSource)); byte abyte0[] = new byte[4096]; int i; while ((i = bufferedinputstream.read(abyte0, 0, 4096)) != -1) out.write(abyte0, 0, i); out.flush(); out.close(); FacesContext.getCurrentInstance().responseComplete(); } catch (IOException ex) { ex.printStackTrace(); } } } -Original Message- From: Aris Bartee [mailto:[EMAIL PROTECTED] Sent: Saturday, April 23, 2005 9:05 AM To: MyFaces Discussion Subject: Re: Download file from browser problem - two clicks I wrapped my download code in an event method: foo(ActionEvent event). The immediate attribute for the uicommand tag should be true. --- Aaron Bartell [EMAIL PROTECTED] wrote: Below is the problem I am still having that I am wondering if anyone has found a solution to. Is there a way to make it so the user doesn't have to click on the same link twice after a file download has occurred? Almost seems like something in the JSF lifecycle isn't completing correctly. I am returning null from action method of the link clicked so I stay on the same page. Any thoughts? Thanks, Aaron Bartell Here is how I have done it based on things I have found on the net. The nice thing about streaming it to the browser is that the file need not exist in your context, it can be anywhere on the file system. The only bummer is that this seems to create a problem after the user downloads. Any button or link that they click after I do the .responseComplete() it doesn't work the first time. But the second time they click the button or link it executes the appropriate code. I am open to suggestions on any errors in my code to fix that problem... private void writeFileToBrowser(String fileSource, String downloadName, String contentType) { if (!FacesContext.getCurrentInstance().getResponseComplete() FileControl.exists(fileSource)) { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); response.setContentType(contentType); response.setHeader(Content-Disposition, attachment;filename=\ + downloadName + \); try { ServletOutputStream out = response.getOutputStream
Re: Download file with jsf
http://www.onjava.com/pub/a/onjava/2005/07/13/jsfupload.html2005/8/20, Carsten Burghardt [EMAIL PROTECTED]:Hi,does anybody know an easy way to stream a file to the browser with jsf? My current solution is a commandLink that calls a blank jsf page with someparameters and this contains a forward to a servlet that does the streaming.The problem is once the user has opened a file, myfaces somehow looses it's navigation state and opens the current page whereever I click next time.Any help appreciated.Carsten
Re: Download file with jsf
Am Saturday 20 August 2005 12:15 schrieb Enrique Medina: http://www.onjava.com/pub/a/onjava/2005/07/13/jsfupload.html Thanks for the link but this is about uploading a file, not downloading. Or is this somehow connected? The download actually works well with the servlet but I have to separate the navigation state of myfaces from the download itself. In the meantime I found a solution that works but needs javascript: the commandLink calls window.open() with the onclick handler and passes the needed parameters to the servlet. But this solution is not very nice as it will cause problems with popup blockers. Carsten
RE: download file+https+tomcat+i exploder
Your last comment is the first direction I would go - check your header content-type (although it should have problems in all the browsers, but I would still double check them). I had a similar problem when writing RPG CGI code on an iSeries machine and I think it was two part - I had the wrong content-type and I didn't have two carriage return line feeds after the header (doh!). HTH, Aaron Bartell -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Sent: Thursday, June 02, 2005 4:43 AM To: users@myfaces.apache.org Subject: download file+https+tomcat+i exploder hi maybe someone faced folowing internet exploder bug: we have dowload page with links to download somme files. app runs on https. in opera, firefox, mozilla user can download file without any problem but #$%^ exploder says that it cant find file:/ we have googledout that problem may occurs because when server sends file to user then in header pragma cache-control=no-cache. and when unsin https than exploder cant see file. can i change that heder in jsf engine (or sth)? slawek
Re: Download file from browser problem - two clicks
The reason the user has to click twice is because the application state is not getting saved properly for some reason. My advice would be to just give the user an h:outputLink / to your file rather than writing it out yourself. On 4/22/05, Aaron Bartell [EMAIL PROTECTED] wrote: Below is the problem I am still having that I am wondering if anyone has found a solution to. Is there a way to make it so the user doesn't have to click on the same link twice after a file download has occurred? Almost seems like something in the JSF lifecycle isn't completing correctly. I am returning null from action method of the link clicked so I stay on the same page. Any thoughts? Thanks, Aaron Bartell Here is how I have done it based on things I have found on the net. The nice thing about streaming it to the browser is that the file need not exist in your context, it can be anywhere on the file system. The only bummer is that this seems to create a problem after the user downloads. Any button or link that they click after I do the .responseComplete() it doesn't work the first time. But the second time they click the button or link it executes the appropriate code. I am open to suggestions on any errors in my code to fix that problem... private void writeFileToBrowser(String fileSource, String downloadName, String contentType) { if (!FacesContext.getCurrentInstance().getResponseComplete() FileControl.exists(fileSource)) { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse();response.setContentType(contentType);response.setHeader(Content-Disposition, attachment;filename=\ + downloadName + \); try { ServletOutputStream out = response.getOutputStream();BufferedInputStream bufferedinputstream = new BufferedInputStream(new FileInputStream( fileSource));byte abyte0[] = new byte[4096]; int i;while ((i = bufferedinputstream.read(abyte0, 0, 4096)) != -1)out.write(abyte0, 0, i); out.flush(); out.close(); FacesContext.getCurrentInstance().responseComplete(); } catch (IOException ex) { ex.printStackTrace(); } } } public static boolean exists(String fileSource) { File f = new File(fileSource); return f.exists (); } HTH, Aaron Bartell Patrick B Haggood wrote: Anyone have an example of downloading using MyFaces? I see on the sample you can use outputtext components, but that's using the real filename (which I keep in a datastore to guard against duplicatefilenames; the system assigns new filename, FILE0002, FILE0003, etc apon upload) Thanks! -- -Heath Borders-Wing[EMAIL PROTECTED]
RE: Download file from browser problem - two clicks
Aaron, Don't have a fix for you, but why don't you just write a specific servlet for downloading files? Don't have to mess with JSF lifecycle and you don't have to put your downloadable files under app context. Kalle From: Aaron Bartell [mailto:[EMAIL PROTECTED] Sent: Monday, April 25, 2005 6:41 AMTo: 'MyFaces Discussion'; [EMAIL PROTECTED]Subject: RE: Download file from browser problem - two clicks That is the way I originally had it a couple months ago, but I have a large repository of documents and to do what you are suggesting I would need to store them in my context which would make war deployment incredibly painful. Because of this I now store the files outside of the apps context and just stream it out to the user. I am guessing it has something to do with me using the responseComplete() method but as of right now I have a beginners knowledge of the guts of the JSF lifecycle and am not sure where to check and see the session state malfunctioning. Note that I get zero error messages in my console and I have it set to debug mode. Check this out. I just changed my code to do nothing but get the request map object, check to see if the response is complete, and if not, complete it. The below produces a blank screen (but remains on the same URL). So my next question would be am I doing anything incorrect here by prematurely terminating the response? I am assuming this would skip the render response phase and that is why I get a blank screen. If that is the case then I am guessing the same thing is happening when I try to write a file out to the browser, the render response phase is not getting executed and thus creating the two clicks scenario because it needs to reinitialize something. ??? Am I way off base? public void downloadPDF(ActionEvent event) { Document doc = (Document) UIHelper.getReqMapObj("document"); if (!FacesContext.getCurrentInstance().getResponseComplete()) FacesContext.getCurrentInstance().responseComplete(); } Thanks to everyone that has responded, Aaron Bartell From: Heath Borders [mailto:[EMAIL PROTECTED] Sent: Monday, April 25, 2005 8:02 AMTo: MyFaces DiscussionSubject: Re: Download file from browser problem - two clicks The reason the user has to click twice is because the application state is not getting saved properly for some reason. My advice would be to just give the user an h:outputLink / to your file rather than writing it out yourself. On 4/22/05, Aaron Bartell [EMAIL PROTECTED] wrote: Below is the problem I am still having that I am wondering if anyone has found a solution to. Is there a way to make it so the user doesn't have to click on the same link twice after a file download has occurred? Almost seems like something in the JSF lifecycle isn't completing correctly. I am returning null from action method of the link clicked so I stay on the same page. Any thoughts? Thanks, Aaron Bartell Here is how I have done it based on things I have found on the net. The nice thing about streaming it to the browser is that the file need not exist in your context, it can be anywhere on the file system. The only bummer is that this seems to create a problem after the user downloads. Any button or link that they click after I do the .responseComplete() it doesn't work the first time. But the second time they click the button or link it executes the appropriate code. I am open to suggestions on any errors in my code to fix that problem... private void writeFileToBrowser(String fileSource, String downloadName, String contentType) { if (!FacesContext.getCurrentInstance().getResponseComplete() FileControl.exists(fileSource)) {HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse();response.setContentType(contentType);response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadName + "\""); try {ServletOutputStream out = response.getOutputStream();BufferedInputStream bufferedinputstream = new BufferedInputStream(new FileInputStream(fileSource));byte abyte0[] = new byte[4096]; int i;while ((i = bufferedinputstream.read(abyte0, 0, 4096)) != -1)out.write(abyte0, 0, i); out.flush(); out.close(); FacesContext.getCurrentInstance().responseComplete(); } catch (IOException ex) { ex.printStackTrace(); } } } public static boolean exists(String fileSource) { File f = new File(fileSource); return f.exists(); } HTH,Aaron Bartell Patrick B Haggood wrote: Anyone have an example of downloading using MyFaces? I see on thesample you can use outputtext components, but that's using the realfilename (which I keep in a datasto
RE: Download file from browser problem - two clicks
That is actually an approach I considered, but the user will either have to be forwarded to that page or a pop-up window will be created and I didnt want the user to have to close an extra window. Silly stuff I know, but I can guarantee the users will complain about that J Actually, thinking about the popup window some more, maybe I could do a onPageLoad _javascript_ that closes the window after the user has been prompted to download the file. hmmm. . . I think you may have led me to my answer! Thanks Kalle! I will post the code once I am done for archive purposes. Aaron Bartell From: Korhonen, Kalle [mailto:[EMAIL PROTECTED] Sent: Monday, April 25, 2005 12:14 PM To: MyFaces Discussion Subject: RE: Download file from browser problem - two clicks Aaron, Don't have a fix for you, but why don't you just write a specific servlet for downloading files? Don't have to mess with JSF lifecycle and you don't have to put your downloadable files under app context. Kalle From: Aaron Bartell [mailto:[EMAIL PROTECTED] Sent: Monday, April 25, 2005 6:41 AM To: 'MyFaces Discussion'; [EMAIL PROTECTED] Subject: RE: Download file from browser problem - two clicks That is the way I originally had it a couple months ago, but I have a large repository of documents and to do what you are suggesting I would need to store them in my context which would make war deployment incredibly painful. Because of this I now store the files outside of the apps context and just stream it out to the user. I am guessing it has something to do with me using the responseComplete() method but as of right now I have a beginners knowledge of the guts of the JSF lifecycle and am not sure where to check and see the session state malfunctioning. Note that I get zero error messages in my console and I have it set to debug mode. Check this out. I just changed my code to do nothing but get the request map object, check to see if the response is complete, and if not, complete it. The below produces a blank screen (but remains on the same URL). So my next question would be am I doing anything incorrect here by prematurely terminating the response? I am assuming this would skip the render response phase and that is why I get a blank screen. If that is the case then I am guessing the same thing is happening when I try to write a file out to the browser, the render response phase is not getting executed and thus creating the two clicks scenario because it needs to reinitialize something. ??? Am I way off base? public void downloadPDF(ActionEvent event) { Document doc = (Document) UIHelper.getReqMapObj(document); if (!FacesContext.getCurrentInstance().getResponseComplete()) FacesContext.getCurrentInstance().responseComplete(); } Thanks to everyone that has responded, Aaron Bartell From: Heath Borders [mailto:[EMAIL PROTECTED] Sent: Monday, April 25, 2005 8:02 AM To: MyFaces Discussion Subject: Re: Download file from browser problem - two clicks The reason the user has to click twice is because the application state is not getting saved properly for some reason. My advice would be to just give the user an h:outputLink / to your file rather than writing it out yourself. On 4/22/05, Aaron Bartell [EMAIL PROTECTED] wrote: Below is the problem I am still having that I am wondering if anyone has found a solution to. Is there a way to make it so the user doesn't have to click on the same link twice after a file download has occurred? Almost seems like something in the JSF lifecycle isn't completing correctly. I am returning null from action method of the link clicked so I stay on the same page. Any thoughts? Thanks, Aaron Bartell Here is how I have done it based on things I have found on the net. The nice thing about streaming it to the browser is that the file need not exist in your context, it can be anywhere on the file system. The only bummer is that this seems to create a problem after the user downloads. Any button or link that they click after I do the .responseComplete() it doesn't work the first time. But the second time they click the button or link it executes the appropriate code. I am open to suggestions on any errors in my code to fix that problem... private void writeFileToBrowser(String fileSource, String downloadName, String contentType) { if (!FacesContext.getCurrentInstance().getResponseComplete() FileControl.exists(fileSource)) { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); response.setContentType(contentType); response.setHeader(Content-Disposition, attachment;filename=\ + downloadName + \); try { ServletOutputStream out = response.getOutputStream(); BufferedInputStream bufferedinputstream = new BufferedInputStream(new FileInputStream( fileSource)); byte abyte0[] = new byte[4096]; int i; while ((i = bufferedinputstream.read(abyte0, 0, 4096)) != -1
Re: Download file from browser problem - two clicks
I wrapped my download code in an event method: foo(ActionEvent event). The immediate attribute for the uicommand tag should be true. --- Aaron Bartell [EMAIL PROTECTED] wrote: Below is the problem I am still having that I am wondering if anyone has found a solution to. Is there a way to make it so the user doesn't have to click on the same link twice after a file download has occurred? Almost seems like something in the JSF lifecycle isn't completing correctly. I am returning null from action method of the link clicked so I stay on the same page. Any thoughts? Thanks, Aaron Bartell Here is how I have done it based on things I have found on the net. The nice thing about streaming it to the browser is that the file need not exist in your context, it can be anywhere on the file system. The only bummer is that this seems to create a problem after the user downloads. Any button or link that they click after I do the .responseComplete() it doesn't work the first time. But the second time they click the button or link it executes the appropriate code. I am open to suggestions on any errors in my code to fix that problem... private void writeFileToBrowser(String fileSource, String downloadName, String contentType) { if (!FacesContext.getCurrentInstance().getResponseComplete() FileControl.exists(fileSource)) { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); response.setContentType(contentType); response.setHeader(Content-Disposition, attachment;filename=\ + downloadName + \); try { ServletOutputStream out = response.getOutputStream(); BufferedInputStream bufferedinputstream = new BufferedInputStream(new FileInputStream( fileSource)); byte abyte0[] = new byte[4096]; int i; while ((i = bufferedinputstream.read(abyte0, 0, 4096)) != -1) out.write(abyte0, 0, i); out.flush(); out.close(); FacesContext.getCurrentInstance().responseComplete(); } catch (IOException ex) { ex.printStackTrace(); } } } public static boolean exists(String fileSource) { File f = new File(fileSource); return f.exists(); } HTH, Aaron Bartell Patrick B Haggood wrote: Anyone have an example of downloading using MyFaces? I see on the sample you can use outputtext components, but that's using the real filename (which I keep in a datastore to guard against duplicate filenames; the system assigns new filename, FILE0002, FILE0003, etc apon upload) Thanks! __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com
RE: Download file from browser problem - two clicks
Thanks for responding Aris, I have implemented what you suggested and am still getting the same problem (note I am using MyFaces 1.0.7). Have I implemented it below the way you have it? I put an actionListener on my commandLink and use an ActionEvent method to capture the line of the dataTable that they selected. I then call writeFileToBrowser and at the end specify FacesContext.getCurrentInstance().responseComplete(). Do you see where I may have something wrong? h:commandLink actionListener=#{DocumentCtl.downloadPDF} immediate=true h:outputText value=view styleClass=copy/ /h:commandLink public void downloadPDF(ActionEvent event) { Document doc = (Document) UIHelper.getReqMapObj(document); String file = Sysctl.getRecord().getLowresfolder() + doc.getGuid() + .pdf; writeFileToBrowser(file, doc.getName() + .pdf, doc.getUploadtype()); } private void writeFileToBrowser(String fileSource, String downloadName, String contentType) { if (!FacesContext.getCurrentInstance().getResponseComplete() FileControl.exists(fileSource)) { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); response.setContentType(contentType); response.setHeader(Content-Disposition, attachment;filename=\ + downloadName + \); try { ServletOutputStream out = response.getOutputStream(); BufferedInputStream bufferedinputstream = new BufferedInputStream( new FileInputStream(fileSource)); byte abyte0[] = new byte[4096]; int i; while ((i = bufferedinputstream.read(abyte0, 0, 4096)) != -1) out.write(abyte0, 0, i); out.flush(); out.close(); FacesContext.getCurrentInstance().responseComplete(); } catch (IOException ex) { ex.printStackTrace(); } } } -Original Message- From: Aris Bartee [mailto:[EMAIL PROTECTED] Sent: Saturday, April 23, 2005 9:05 AM To: MyFaces Discussion Subject: Re: Download file from browser problem - two clicks I wrapped my download code in an event method: foo(ActionEvent event). The immediate attribute for the uicommand tag should be true. --- Aaron Bartell [EMAIL PROTECTED] wrote: Below is the problem I am still having that I am wondering if anyone has found a solution to. Is there a way to make it so the user doesn't have to click on the same link twice after a file download has occurred? Almost seems like something in the JSF lifecycle isn't completing correctly. I am returning null from action method of the link clicked so I stay on the same page. Any thoughts? Thanks, Aaron Bartell Here is how I have done it based on things I have found on the net. The nice thing about streaming it to the browser is that the file need not exist in your context, it can be anywhere on the file system. The only bummer is that this seems to create a problem after the user downloads. Any button or link that they click after I do the .responseComplete() it doesn't work the first time. But the second time they click the button or link it executes the appropriate code. I am open to suggestions on any errors in my code to fix that problem... private void writeFileToBrowser(String fileSource, String downloadName, String contentType) { if (!FacesContext.getCurrentInstance().getResponseComplete() FileControl.exists(fileSource)) { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); response.setContentType(contentType); response.setHeader(Content-Disposition, attachment;filename=\ + downloadName + \); try { ServletOutputStream out = response.getOutputStream(); BufferedInputStream bufferedinputstream = new BufferedInputStream(new FileInputStream( fileSource)); byte abyte0[] = new byte[4096]; int i; while ((i = bufferedinputstream.read(abyte0, 0, 4096)) != -1) out.write(abyte0, 0, i); out.flush(); out.close(); FacesContext.getCurrentInstance().responseComplete(); } catch (IOException ex) { ex.printStackTrace(); } } } public static boolean exists(String fileSource) { File f = new File(fileSource); return f.exists(); } HTH, Aaron Bartell Patrick B Haggood wrote: Anyone have an example of downloading using MyFaces? I see on the sample you can use outputtext components, but that's using the real filename (which I keep in a datastore to guard against duplicate filenames; the system assigns new filename, FILE0002
RE: Download file from browser problem - two clicks
I'm sorry. My reply was from memory. I used the action listener tag inside of a command link. Here's the snippet: h:commandLink value=#{file} action=downloadfile h:outputText value=#{file} jsf:converter converterId=FileNameConverter/ /h:outputText jsf:actionListener type=pamcep.jsf.event.RetrieveFile/ /h:commandLink The version I used this with is 1.03. --- [EMAIL PROTECTED] wrote: Thanks for responding Aris, I have implemented what you suggested and am still getting the same problem (note I am using MyFaces 1.0.7). Have I implemented it below the way you have it? I put an actionListener on my commandLink and use an ActionEvent method to capture the line of the dataTable that they selected. I then call writeFileToBrowser and at the end specify FacesContext.getCurrentInstance().responseComplete(). Do you see where I may have something wrong? h:commandLink actionListener=#{DocumentCtl.downloadPDF} immediate=true h:outputText value=view styleClass=copy/ /h:commandLink public void downloadPDF(ActionEvent event) { Document doc = (Document) UIHelper.getReqMapObj(document); String file = Sysctl.getRecord().getLowresfolder() + doc.getGuid() + .pdf; writeFileToBrowser(file, doc.getName() + .pdf, doc.getUploadtype()); } private void writeFileToBrowser(String fileSource, String downloadName, String contentType) { if (!FacesContext.getCurrentInstance().getResponseComplete() FileControl.exists(fileSource)) { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); response.setContentType(contentType); response.setHeader(Content-Disposition, attachment;filename=\ + downloadName + \); try { ServletOutputStream out = response.getOutputStream(); BufferedInputStream bufferedinputstream = new BufferedInputStream( new FileInputStream(fileSource)); byte abyte0[] = new byte[4096]; int i; while ((i = bufferedinputstream.read(abyte0, 0, 4096)) != -1) out.write(abyte0, 0, i); out.flush(); out.close(); FacesContext.getCurrentInstance().responseComplete(); } catch (IOException ex) { ex.printStackTrace(); } } } -Original Message- From: Aris Bartee [mailto:[EMAIL PROTECTED] Sent: Saturday, April 23, 2005 9:05 AM To: MyFaces Discussion Subject: Re: Download file from browser problem - two clicks I wrapped my download code in an event method: foo(ActionEvent event). The immediate attribute for the uicommand tag should be true. --- Aaron Bartell [EMAIL PROTECTED] wrote: Below is the problem I am still having that I am wondering if anyone has found a solution to. Is there a way to make it so the user doesn't have to click on the same link twice after a file download has occurred? Almost seems like something in the JSF lifecycle isn't completing correctly. I am returning null from action method of the link clicked so I stay on the same page. Any thoughts? Thanks, Aaron Bartell Here is how I have done it based on things I have found on the net. The nice thing about streaming it to the browser is that the file need not exist in your context, it can be anywhere on the file system. The only bummer is that this seems to create a problem after the user downloads. Any button or link that they click after I do the .responseComplete() it doesn't work the first time. But the second time they click the button or link it executes the appropriate code. I am open to suggestions on any errors in my code to fix that problem... private void writeFileToBrowser(String fileSource, String downloadName, String contentType) { if (!FacesContext.getCurrentInstance().getResponseComplete() FileControl.exists(fileSource)) { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); response.setContentType(contentType); response.setHeader(Content-Disposition, attachment;filename=\ + downloadName + \); try { ServletOutputStream out = response.getOutputStream(); BufferedInputStream bufferedinputstream = new BufferedInputStream(new FileInputStream( fileSource)); byte abyte0[] = new byte[4096]; int i; while ((i = bufferedinputstream.read(abyte0, 0, 4096)) != -1) out.write(abyte0, 0, i); out.flush(); out.close