How to provide a file download from a JSF backing bean?

前端 未结 4 1102
我在风中等你
我在风中等你 2020-11-21 07:26

Is there any way of providing a file download from a JSF backing bean action method? I have tried a lot of things. Main problem is that I cannot figure how to get the

4条回答
  •  故里飘歌
    2020-11-21 07:45

    here is the complete code snippet http://bharatonjava.wordpress.com/2013/02/01/downloading-file-in-jsf-2/

     @ManagedBean(name = "formBean")
     @SessionScoped
     public class FormBean implements Serializable
     {
       private static final long serialVersionUID = 1L;
    
       /**
        * Download file.
        */
       public void downloadFile() throws IOException
       {
          File file = new File("C:\\docs\\instructions.txt");
          InputStream fis = new FileInputStream(file);
          byte[] buf = new byte[1024];
          int offset = 0;
          int numRead = 0;
          while ((offset < buf.length) && ((numRead = fis.read(buf, offset, buf.length -offset)) >= 0)) 
          {
            offset += numRead;
          }
          fis.close();
          HttpServletResponse response =
             (HttpServletResponse) FacesContext.getCurrentInstance()
            .getExternalContext().getResponse();
    
         response.setContentType("application/octet-stream");
         response.setHeader("Content-Disposition", "attachment;filename=instructions.txt");
         response.getOutputStream().write(buf);
         response.getOutputStream().flush();
         response.getOutputStream().close();
         FacesContext.getCurrentInstance().responseComplete();
       }
     }
    

    You may change the file reading logic in case you want file to get generated at runtime.

提交回复
热议问题