Question

Just starting to learn how to do the download with jsf. I have looked at couple other related posts. And mainly copy their code, but it seems like I did something wrong.
This is my code

public void download() throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setHeader("Content-disposition", "attachment;filename=\"001.cvf\""); // The Save As popup magic is done here. You can give it any filename you want, this only won't work in MSIE, it will use current request URL as filename instead.

    BufferedInputStream input = null;
    BufferedOutputStream output = null;
    String content =VCFHandler.getContent(profile.getFriendlist());
    response.setHeader("Content-Length", String.valueOf(content.length()));
    try {
        InputStream stream = new ByteArrayInputStream(content.getBytes("UTF-8"));
        input = new BufferedInputStream(stream);
        output = new BufferedOutputStream(response.getOutputStream());

        byte[] buffer = new byte[10240];
        for (int length; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }
        output.flush();
    } finally {
        output.close();
        input.close();
    }

    facesContext.responseComplete(); // Important! Else JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

So I tried this code with debugger in eclipse. When download button is clicked, this method is called (which is what I wanted). But after all steps are finished no popup is shown in my page. Anyone have any suggestions? BTW the content type is

private final static String contentType="text/x-vcard";
Was it helpful?

Solution

By your problem description, I'm not sure but looks like you're firing the download from an ajax request. Remove the ajax behavior for this request and try again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top