struts and file download

Discussion in 'Java' started by MileHighCelt, Jan 18, 2006.

  1. MileHighCelt

    MileHighCelt Guest

    I am getting an Outputstream already obtained when my Action passes the
    HttpServletResponse to another method, which then does:

    response.setContentType("text/csv");
    response.setHeader("Content-disposition",
    attachment.toString());
    response.setHeader("Pragma", null);
    response.setHeader("Cache-Control","no-store");

    ....
    OutputStream os = response.getOutputStream();
    ....
    os.write(s.getBytes()); // where s is a String;


    then it writes some strings to that stream. The problem seems to
    be that somewhere after this code the IllegalStateException is being
    thrown. I am trapping it in my code but it isn't occuring there.

    So my question is, what is the preferred method of returning a file for
    the user to download when they click a button/link to trigger this
    action? Is struts already using the HttpServletResponse and triggering
    all these exceptions?
     
    MileHighCelt, Jan 18, 2006
    #1
    1. Advertising

  2. MileHighCelt

    MileHighCelt Guest

    Nevermind - I found that if I use a printwriter instead of the
    OutputStream this clears up. For those looking for a solution, try :

    StringBuffer attachment = new StringBuffer();

    attachment.append("attachment;filename=").append(file.getName());
    try {
    response.setContentType(contentType);
    response.setContentLength((int) file.length());
    response.setHeader("Content-disposition", attachment.toString());
    java.io.PrintWriter os = response.getWriter();

    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line;

    char[] buffer = new char[4096];
    int read = 0;

    while((read = reader.read(buffer))>0) {
    line = new String(buffer,0,read);
    os.write(line);
    }
    os.flush();
    close();
    reader.close();
     
    MileHighCelt, Jan 19, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ryan Taylor
    Replies:
    2
    Views:
    953
    Ryan Taylor
    Nov 10, 2004
  2. Sam --
    Replies:
    2
    Views:
    617
    Sam --
    Mar 17, 2005
  3. Katie Wright
    Replies:
    8
    Views:
    4,252
    Andrea Desole
    Jan 7, 2005
  4. Brett  Kelly
    Replies:
    1
    Views:
    684
    Steve C. Orr [MVP, MCSD]
    Jun 16, 2006
  5. ros
    Replies:
    0
    Views:
    604
Loading...

Share This Page