struts and file download

M

MileHighCelt

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?
 
M

MileHighCelt

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();
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top