Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

download file in servlets 1

Status
Not open for further replies.

javanemo

Technical User
Sep 9, 2003
14
AU
I am planning to write a code to downlaod an excel file in c:\tmp
Anyone has any idea how will I be able to achieve that as the c:\tmp is not deployed in Tomcat?
Any example codes that anyone can provide me?
 
Do you mean upload a file from a client browser to the server, or download a server file to the client machine ?
 
the file will be stored in c:/tmp in the server computer.
The client will be able to download the file when he clicks on a button.
I need to write code for the user to download the file. I have really no idea how to approach this method.
 
I tot of that but I do not want people to find out the link as it may contain some private stuff. This will only be accessible only from a login page. Therefore I was thinking of storing the file in a local drive which is not deployable in Tomcat.
 
is there a way all the servlets is totally unable to do that unless we deploy it?
If we have to put it on the web server then it would be simple. We can just redirect the servlet to the filename itself. But this is not what I wanted.
Any codes that will be able to solve this issue?
 
Well, you can configure your web/app server (JBoss, Tomcat, Apache etc) to protect files under a certain context path - so that if someone is not logged in, they cannot access the files ... this seems a much more efficient way of doing it - using your web server for the job it was designed to do !

However,

if you do insist on going down the other route, you need to have a servlet which, when servicing a requests does the following (in doPost()/doGet()):

Determine the file (C:/tmp/afile or whatever) to load.
Create a FileInputStream, and read the entire file into a byte array.
Then create an OutputStream to the browser, and write the byte data -

Code:
File file = new File("somefile");
FileInputStream fis = new FileInputStream(file));
byte[] buffer = new byte[(int)file.size()];
fis.read(buffer, 0, buffer.length);

OutputStream os = response.getOutputStream();
out.write(buffer);
out.flush();
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top