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

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

    This is what worked for me:

    public void downloadFile(String filename) throws IOException {
        final FacesContext fc = FacesContext.getCurrentInstance();
        final ExternalContext externalContext = fc.getExternalContext();
    
        final File file = new File(filename);
    
        externalContext.responseReset();
        externalContext.setResponseContentType(ContentType.APPLICATION_OCTET_STREAM.getMimeType());
        externalContext.setResponseContentLength(Long.valueOf(file.lastModified()).intValue());
        externalContext.setResponseHeader("Content-Disposition", "attachment;filename=" + file.getName());
    
        final HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    
        FileInputStream input = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        final ServletOutputStream out = response.getOutputStream();
    
        while ((input.read(buffer)) != -1) {
            out.write(buffer);
        }
    
        out.flush();
        fc.responseComplete();
    }
    

提交回复
热议问题