刚开始学习如何使用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中使用调试器尝试了这段代码。单击下载按钮时,将调用此方法(这是我想要的)。但是在完成所有步骤后,我的页面中没有显示弹出窗口。有人有什么建议吗? BTW内容类型是
private final static String contentType="text/x-vcard";
答案 0 :(得分:1)
根据您的问题描述,我不确定,但看起来您正在从ajax请求中解除下载。删除此请求的ajax行为,然后重试。