-1

I have the below button:

<h:commandButton value="Download" action="#{listFiles.downloadFile}" />

And the below action method:

public void downloadFile()
    {
        // Some code.
    }

But when I press the button nothing happens. The action method is not invoked.

In the server log I see:

The form component needs to have a UIForm in its ancestry. Suggestion: enclose the necessary components within <h:form>

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

1 Answers1

1

this work for me

My file in folder path

WEB-INF\pages\forms

cod in xhtml file

<h:commandLink value="Download" action="#{formBean.downloadFile('FileName.doc')}" styleClass="link"/>

beans

public String downloadFile(String fileName) {
        try {
            FacesContext facesContext = FacesContext.getCurrentInstance();
            HttpServletResponse response = ((HttpServletResponse) facesContext.getExternalContext().getResponse());
            String reportPath = facesContext.getExternalContext().getRealPath("\\pages\\forms") + File.separator + fileName;

            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName+ "\"");

            File file = new File(reportPath);

            BufferedInputStream bIn = new BufferedInputStream(new FileInputStream(file));

            int rLength = -1;

            byte[] buffer = new byte[1000];

            while ((rLength = bIn.read(buffer, 0, 100)) != -1) {
                response.getOutputStream().write(buffer, 0, rLength);
            }

            FacesContext.getCurrentInstance().responseComplete();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
Sai prateek
  • 11,842
  • 9
  • 51
  • 66
Ömer Faruk Kurt
  • 500
  • 3
  • 14