views:

147

answers:

1

Hi I've tried two different techniques for sending a file to a browser(making the user download a file). I've tried an example from 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();

I have also tried using a component named fileDownload from PrimeFaces. Both give the same result:

I get a response from the server, the response contains text that should be in the file. The header is a follows:

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

To me this looks correct but for some reason I don't get to download the file, I just get this response in firebug.

Does anyone have any idea?, could it be a serversetting problem? I using glassfish 3

Thanks / Stefan

A: 

Sounds like as if you're requesting this asynchronously (using Ajax) instead of synchronously. When you do so, then you will indeed never see the Save As dialogue. You should always request file downloads synchronously. I.e. use "plain vanilla" h:commandLink or h:commandButton for this instead of some ajaxical command component.

BalusC
Jepp that was the problem
Stefan