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

前端 未结 4 1056
我在风中等你
我在风中等你 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:59

    public void download() throws IOException
    {
    
        File file = new File("file.txt");
    
        FacesContext facesContext = FacesContext.getCurrentInstance();
    
        HttpServletResponse response = 
                (HttpServletResponse) facesContext.getExternalContext().getResponse();
    
        response.reset();
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=file.txt");
    
        OutputStream responseOutputStream = response.getOutputStream();
    
        InputStream fileInputStream = new FileInputStream(file);
    
        byte[] bytesBuffer = new byte[2048];
        int bytesRead;
        while ((bytesRead = fileInputStream.read(bytesBuffer)) > 0) 
        {
            responseOutputStream.write(bytesBuffer, 0, bytesRead);
        }
    
        responseOutputStream.flush();
    
        fileInputStream.close();
        responseOutputStream.close();
    
        facesContext.responseComplete();
    
    }
    

提交回复
热议问题