您好,我尝试了两种不同的技术来将文件发送到浏览器(让用户下载文件)。我尝试了一个来自myfaces wikipage的例子
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
int read = 0;
byte[] bytes = new byte[1024];
String fileName = "test.txt";
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
OutputStream os = null;
StringBuffer stringBuffer1 = new StringBuffer("Java Forums rock");
ByteArrayInputStream bis1;
try {
bis1 = new ByteArrayInputStream(stringBuffer1.toString().getBytes("UTF-8"));
os = response.getOutputStream();
while ((read = bis1.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
FacesContext.getCurrentInstance().responseComplete();我还尝试使用了PrimeFaces的一个名为fileDownload的组件。两者都会产生相同的结果:
我从服务器得到一个响应,该响应包含文件中应该包含的文本。标头是以下内容:
X-Powered-By Servlet/3.0, JSF/2.0
Server GlassFish v3
Content-Disposition attachment;filename="test.txt"
Content-Type text/plain
Transfer-Encoding chunked
Date Thu, 20 May 2010 06:30:20 GMT对我来说,这看起来是正确的,但由于某种原因,我无法下载文件,我只是在firebug中得到了这个响应。
有谁知道吗?这可能是服务器设置的问题吗?我使用glassfish 3
谢谢/ Stefan
发布于 2010-05-20 20:18:57
听起来好像是异步请求(使用Ajax),而不是同步请求。当你这样做的时候,你将永远看不到“另存为”对话框。您应该始终同步请求文件下载。也就是说,使用“普通的”h:commandLink或h:commandButton来代替一些简单的命令组件。
https://stackoverflow.com/questions/2871524
复制相似问题