0

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

谢谢/斯特凡

4

1 回答 1

3

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

于 2010-05-20T12:18:56.797 回答