wood burning stoves 2.0*
The moose likes Servlets and the fly likes How do I execute a file download from a servlet? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Servlets
Bookmark "How do I execute a file download from a servlet?" Watch "How do I execute a file download from a servlet?" New topic
Author

How do I execute a file download from a servlet?

P.Jamieson
Greenhorn

Joined: Apr 30, 2003
Posts: 21
I would like to have a file download in my web application. I am using a servlet for processing requests. As part a user request is to initiate a file download. I just want to have a bit more control of downloading rather than inputting a hyperlink into the browser. At the moment I do not have FTP and probably will not for now, thanks
Anthony Watson
Ranch Hand

Joined: Sep 25, 2003
Posts: 327
You can use the following methods to allow your servlet to respond to a request with a file instead of some html:
//put in whatever type of file you are sending in place of text/plain
response.setContentType("text/plain");

InputStream is = request.getInputStream();
File f = new File(getServletContext().getRealPath("myFile.txt"));
byte[] fileBytes = new byte[(int)f.length()];

is.read(fileBytes);

ServletOutputStream out = response.getOutputStream();
out.write(fileBytes);
response.flushBuffer();


Anthony W.<br />MCP, SCJP 1.4, SCJD, SCWCD 1.3, SCWCD 1.4, SCBCD
P.Jamieson
Greenhorn

Joined: Apr 30, 2003
Posts: 21
I have tried using using this code and it works fine except that my filename in the download dialog is a text file rather than the ZIP file that I experimenting with. Also the name of the file does not match. If I do the same request from HTML I get the proper name and extension to display in the dialog. Any suggestions?
 
GeeCON Prague 2014
 
subject: How do I execute a file download from a servlet?