首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试使用JSF将文件发送到浏览器时出现问题

尝试使用JSF将文件发送到浏览器时出现问题
EN

Stack Overflow用户
提问于 2010-05-20 14:44:21
回答 1查看 3.1K关注 0票数 0

您好,我尝试了两种不同的技术来将文件发送到浏览器(让用户下载文件)。我尝试了一个来自myfaces wikipage的例子

代码语言:javascript
复制
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的组件。两者都会产生相同的结果:

我从服务器得到一个响应,该响应包含文件中应该包含的文本。标头是以下内容:

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-05-20 20:18:57

听起来好像是异步请求(使用Ajax),而不是同步请求。当你这样做的时候,你将永远看不到“另存为”对话框。您应该始终同步请求文件下载。也就是说,使用“普通的”h:commandLinkh:commandButton来代替一些简单的命令组件。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2871524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档