开发者

Primefaces fileDownload - getOutputStream() has already been called for this response

开发者 https://www.devze.com 2023-04-12 15:08 出处:网络
I\'m using Primefaces fileDownload. When I first start the application the file is downloaded but then everytime I press the download button, this error appears:

I'm using Primefaces fileDownload. When I first start the application the file is downloaded but then everytime I press the download button, this error appears:

java.lang.IllegalStateException: getOutputStream() has already been called for this response

My xhtml code:

   <p:commandButton value="Download" ajax="true">
         <p:fileDownload value="#{fileDownloadController.file}" />
   </p:commandButton> 

My java code:

        private StreamedContent file;

        public FileDownloadController() {
            InputStream stream = null;
            try {
开发者_运维知识库                stream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/Enastr1.txt");
                file = new DefaultStreamedContent(stream, "txt", "Downloaded_Enastr1");
            } catch (Exception ex) {
                Logger.getLogger(FileDownloadController.class.getName()).log(Level.SEVERE, null, ex);
            } finally {

            }
        }

        public StreamedContent getFile() {
            return file;
        }

        public void setFile(StreamedContent file) {
            this.file = file;
        }


You're creating the stream in the constructor of the bean instead of in the action method associated with the <p:commandButton>. The symptoms indicate that the bean is placed in a broader scope than the request scope. The constructor is only called upon bean's construction, not on every HTTP request. If the bean is put in the request scope, then the constructor is called on every HTTP request.

You have 2 options:

  1. Put the bean in the request scope.

  2. Create the stream in an action method instead and bind it to <p:commandButton action>.


Are there multiple <p:filedownload/> tags in your page (possibly with the same binding)? I had issues with Primefaces when attempting to use multiple ajax-enabled <p:filedownload/> tags (bound to different properties in the backing bean) in the same page with other ajax-y functionality. The main problem seemed to be that every <p:filedownload/> became bound to the same property. My project's requirements changed in a way that removed the need for ajax downloads, so I don't have a good solution for you, but this might help you on your way.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号