• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How do I execute a file download from a servlet?

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
reply
    Bookmark Topic Watch Topic
  • New Topic