File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do I execute a file download from a servlet?

 
P.Jamieson
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 327
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
 
P.Jamieson
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic