jsf 2 - JSF response.setHeader "Content-disposition" no popup



刚刚开始学习如何用jsf进行下载。我看过其他几个相关帖子。并且主要是复制他们的代码,但似乎我做错了什么。
这是我的代码

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.
}

所以我在 eclipse 中使用调试器尝试了这段代码。单击下载按钮时,将调用此方法(这是我想要的)。但是在所有步骤完成后,我的页面中不会显示弹出窗口。有人有什么建议吗?顺便说一句,内容类型是

private final static String contentType="text/x-vcard";

根据您的问题描述,我不确定,但看起来您正在从 ajax 请求触发下载。删除此请求的 ajax 行为,然后重试。

相关内容

  • 没有找到相关文章

最新更新