> I am working on a simple web application (jsp/servlet). I would like
> to send a file back to the client without ever creating the file on the
> server. Is there an easy way to do this?
Sure. Don't use a JSP; put this in a servlet. Use
HttpServletResponse.setContentType(String) to set the MIME type for the
result, and then use getOutputStream() to get a stream and write the
result to it. If you don't know the length ahead of time, don't set the
content length and the response will use chunked encoding. Otherwise,
use setContentLength(int) to set the content length header. If you want
to strongly suggest that the client save the file rather than open it
within the browser, google for "Content-Disposition".

Signature
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
grasp06110 - 16 Jan 2006 16:11 GMT
Hi,
Thanks for the help. The writeString method below works well but the
writeFile method does not. The writeFile method executes but data are
not sent to the client. The files I am sending are small so it
shouldn't be an issue for this application but it would be nice to get
the file method to write data to the client.
Thanks again,
Grasp
private void writeString(HttpServletResponse response,
String string) throws Exception {
response.setContentType("application/x-download");
response.setHeader("Content-Disposition",
"attachment; filename=certificate.txt");
PrintWriter out = response.getWriter();
out.write("hello world");
}
private void writeFile(HttpServletResponse response, String string)
throws Exception {
response.setContentType("application/x-download");
response.setHeader("Content-Disposition",
"attachment; filename=certificate.txt");
OutputStream out = response.getOutputStream();
InputStream in = new ByteArrayInputStream(string.getBytes());
int bufferSize = 1024;
BufferedOutputStream dest =
new BufferedOutputStream(out, bufferSize);
int count = 0;
byte[] data = new byte[bufferSize];
System.out.println("writing data");
while ((count = in.read(data, 0, bufferSize)) != -1) {
dest.write(data, 0, count);
System.out.write(data, 0, count);
}
System.out.println("");
out.flush();
out.close();
}