title: Downloading image file using PrimeFaces
body: <p>I have a web application that uses PrimeFaces components. I am trying to download a file from the database to be saved to someones client computer. In the code, I am writing the byte array to the file object shown below. However, I do not know how to trigger the download dialog bar when the function is triggered. Can someone please help?</p>
  
  <p>Download function in Download bean</p>
  
  <pre><code>public void fileDownload(int id) throws IOException {
  
      try {
          Class.forName("com.mysql.jdbc.Driver");
          DBConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demeter2.0", "root", "root");
      } catch (SQLException | ClassNotFoundException ex) {
          Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
      }
  
      PreparedStatement pst = null;
  
      try {
          if (DBConn != null) {
              String sql = "Select * FROM graph WHERE id='" + id + "'";
              pst = (PreparedStatement) DBConn.prepareStatement(sql);
              ResultSet rs = pst.executeQuery();
  
              if (!rs.next()) {
              } else {
                  rs.beforeFirst();
  
                  while (rs.next()) {
                      // File file = new File("c:/newfile.png");
                      Blob b = rs.getBlob(2);
                      byte barr[] = new byte[(int) b.length()];
                      barr = b.getBytes(1, (int) b.length());
                      InputStream is = new ByteArrayInputStream(barr);
                      System.out.print("hello");
                      file = new DefaultStreamedContent(is, "image/png", "chart.png");
                      System.out.print(file);
                  }//end while
              }
          }
      } catch (Exception e) {
          System.out.println(e);
      } finally {
          try {
              pst.close();
              DBConn.close();
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>download.xhtml</p>
  
  <pre><code>&lt;h:form&gt;
      &lt;p:dataTable var="download" value="#{download.allGraph()}"&gt;
          &lt;p:column headerText="Id"&gt;
              &lt;h:outputText value="#{download.id}" /&gt;
          &lt;/p:column&gt;
  
          &lt;p:column headerText="Date Added"&gt;
              &lt;h:outputText value="#{download.date}" /&gt;
          &lt;/p:column&gt;
  
          &lt;p:column headerText="Download"&gt;
              &lt;p:commandLink id="downloadLink" value="Download" ajax="false"&gt;
                  &lt;p:fileDownload value="#{download.fileDownload(download.id)}" /&gt;
              &lt;/p:commandLink&gt;
          &lt;/p:column&gt;
      &lt;/p:dataTable&gt;
  &lt;/h:form&gt;
  </code></pre>