File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes How to initiate a file download or push to client? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "How to initiate a file download or push to client?" Watch "How to initiate a file download or push to client?" New topic

How to initiate a file download or push to client?

Sloan Bowman
Ranch Hand

Joined: Jan 21, 2003
Posts: 107
Hello I wrote a simple form based program that takes the form data passes this information to the Servlet. The Servlet then formats the data into an xml file. What I'm wanting to do is push the xml file to the client so a download or save as box will appear once the file has been created. Any ideas? thanks.
chanoch wiggers
Ranch Hand

Joined: May 24, 2001
Posts: 245
we use this ourselves - here is example code that doesnt show the generation of the actual file. We generate the PDF dynamically and stores the file as bytes in the variable buffer:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

ServletContext context = getServletContext();

String messagename = "whatever.pdf";
messagename = (messagename.indexOf(".pdf") == -1) ? messagename : messagename.substring(0, messagename.indexOf(".pdf"));

response.setHeader("Content-disposition", "attachment; filename=\"Document for " + messagename + "\"");"setting content type to pdf");

response.setContentLength(filesize);"content length is:" + filesize);

OutputStream out = response.getOutputStream();
// write out to output and return. anything that stops the servlet getting to this point will be forwarded to an error page"writing file to output");
} catch(IOException ioe) {
logger.error("Document caused an IO Error Filename:" + filename);
// forward to missing resource.
//on error forward to resource not found.
} else {"could not find resource, forwarding to missing resource page");
String path = context.getInitParameter("resourcemissing");
context.getRequestDispatcher(path).forward(request, response);

chanoch<p><a href="" target="_blank" rel="nofollow">Author of Professional Apache Tomcat</a></p>
I agree. Here's the link:
subject: How to initiate a file download or push to client?
It's not a secret anymore!