Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to initiate a file download or push to client?

 
Sloan Bowman
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
-Sloan
 
chanoch wiggers
Author
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();

response.setContentType("application/pdf");
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 + "\"");
logger.info("setting content type to pdf");

response.setContentLength(filesize);
logger.info("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
logger.info("writing file to output");
out.write(buffer);
return;
}
} catch(IOException ioe) {
logger.error("Document caused an IO Error Filename:" + filename);
// forward to missing resource.
}
//on error forward to resource not found.
} else {
logger.info("could not find resource, forwarding to missing resource page");
String path = context.getInitParameter("resourcemissing");
context.getRequestDispatcher(path).forward(request, response);
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic