【问题标题】:Problem trying to send file to browser in JSF尝试在 JSF 中将文件发送到浏览器时出现问题
【发布时间】:2010-05-20 06:44:20
【问题描述】:

您好,我尝试了两种不同的技术来将文件发送到浏览器(让用户下载文件)。我尝试了 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

谢谢 / 斯特凡

【问题讨论】:

    标签: jsf download jsf-2


    【解决方案1】:

    听起来好像您是异步请求(使用 Ajax)而不是同步请求。当您这样做时,您确实将永远不会看到 Save As 对话框。您应该始终同步请求文件下载。 IE。为此使用“普通香草”h:commandLinkh:commandButton 而不是一些 ajaxical 命令组件。

    【讨论】:

      猜你喜欢
      • 2021-02-27
      • 2017-01-29
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      相关资源
      最近更新 更多