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
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()];
ServletOutputStream out = response.getOutputStream(); out.write(fileBytes); response.flushBuffer();
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?
subject: How do I execute a file download from a servlet?