title: Download file with JSF
body: <p>everyone!</p>
  
  <p>I have a trouble. I tried to save excel file in jsf web application.
  I generated file by my utils and trying to get "save" window, but I failed. </p>
  
  <p>Here is my code:</p>
  
  <pre><code>  &lt;div&gt;
    &lt;h:commandButton value="Apply" actionListener="#{hornPhonesBean.generateReport}"/&gt;
    &lt;/div&gt;
  </code></pre>
  
  <p>and: </p>
  
  <pre><code>   public void generateReport(ActionEvent event) {
      System.out.println("GENERATE REPORT FROM = " + this.dateFrom + "; TO = " + this.dateTo);
  
      try {
          XSSFWorkbook workbook = (XSSFWorkbook) HornReportGenerator.getWorkbook(null, null);
          String fileName = "1.xlsx";
  
          FacesContext fc = FacesContext.getCurrentInstance();
          ExternalContext ec = fc.getExternalContext();
  
          // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
          ec.responseReset(); 
  
          // Check http://www.w3schools.com/media/media_mimeref.asp for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
          ec.setResponseContentType("application/vnd.ms-excel"); 
  
          // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
          //ec.setResponseContentLength(contentLength); 
  
          // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
          ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); 
  
          OutputStream output = ec.getResponseOutputStream();
          workbook.write(output); 
          output.flush();
          output.close();
  
          fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
          System.out.println("END");
      } catch (Exception e) {
          e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>I read suggestions here and from another forums - everyone says I shouldnt use , but I didn't use it at all.</p>
  
  <p>Then I thought that the problem could be in the </p>
  
  <pre><code> &lt;ice:form&gt;, 
  </code></pre>
  
  <p>where I kept the </p>
  
  <pre><code> &lt;h:commandButton&gt;, 
  </code></pre>
  
  <p>and I changed to </p>
  
  <pre><code> &lt;h:form&gt;, 
  </code></pre>
  
  <p>but it didn't help.</p>
  
  <p>Maybe the problem in the request - it has header Faces-Request  partial/ajax. But I am not sure.</p>
  
  <p>Please give me some ideas - I already spent 4 hours for this crazy jsf download issue)</p>