Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Servlets and the fly likes Downloading file through Servlet. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Downloading file through Servlet." Watch "Downloading file through Servlet." New topic
Author

Downloading file through Servlet.

Siva Vu
Greenhorn

Joined: Sep 01, 2004
Posts: 22
Following is the piece of code. fileName is dynamic.
The problem is for smaller files(<1 MB), it is not prompting the dilouge
box to save the file, rather it displayes blank screen. For bigger files, it is prompting and saving the files. IE6.0 browser. Why is it behaving weirdly? Any ideas or any suggestions. Thanks in advance.

FileInputStream fileInput = new FileInputStream(fileName);
int numOfBytes = fileInput.available();
response.setContentLength(numOfBytes);
ServletOutputStream stream = response.getOutputStream();
BufferedInputStream fif = new BufferedInputStream(fileInput);
response.setHeader("Content-Type", "application/comma-separated-values; charset=ISO-8859-1");
response.setHeader("Content-Disposition","attachement;filename=" + fileName);
byte[] buffer = new byte[1024];
while (true) {
int bytesRead = fif.read(buffer, 0, buffer.length);
if (bytesRead < 0)
break;
stream.write(buffer, 0, bytesRead);
}
stream.flush();
stream.close();
fif.close();


Siva
Julian Kennedy
Ranch Hand

Joined: Aug 02, 2004
Posts: 823
Cud it bee yor speling?

Easily done.

Jules
Siva Vu
Greenhorn

Joined: Sep 01, 2004
Posts: 22
Thank you for the reply.

Even after correcting the spelling, it behaves the same way as before.

Does anybody know why it is behaving like this?
Siva Vu
Greenhorn

Joined: Sep 01, 2004
Posts: 22
Added to the previous one, when the SAve as dailouge cancelled on the client side, why the file contents are buffered and writes on the browser screen.
Susanta Chatterjee
Ranch Hand

Joined: Aug 12, 2002
Posts: 102
Please post the HTML Link (or button with script coded) which is responsible to download the file from server. Looks like content target is your current document body - that is the reason - my guess.

Did you see the same behavior on IE 5.x or any other browser?
Siva Vu
Greenhorn

Joined: Sep 01, 2004
Posts: 22
function download()
{

document.pageForm.submit_field.value = "H" ;
document.pageForm.method="POST";
document.pageForm.submit();
}

I am using a button to call this javaScript function,
Servlet pushes created file to client, prompting the user
to save the file. If the user cancels the dailog box, then
the pushed file is buffering(Do not know how it is doing) and
it is prompting to save the file whenever trying to use the
application from the begining(Whenever browser accessing the main page
which is a starting page.)

I am using MSIE 6.0.

Thanks in advance.
[ September 10, 2004: Message edited by: Siva Vu ]
Julia Reynolds
Ranch Hand

Joined: May 31, 2001
Posts: 123
Siva,

I know this sounds weird, but I had the same problem and solved it by switching the order in which I was setting things in the response header. So try changing from this:

response.setHeader("Content-Type", "application/comma-separated-values; charset=ISO-8859-1");
response.setHeader("Content-Disposition","attachement;filename=" + fileName);

to this:
response.setHeader("Content-Disposition","attachment;filename=" + fileName);
response.setHeader("Content-Type", "application/comma-separated-values; charset=ISO-8859-1");


Good Luck,

Julia
Saritha Penumudi
Ranch Hand

Joined: Aug 18, 2003
Posts: 147
Hi,
I m following this thread and i have a similar requirement where I have to enable client to download a data from the database into a file.

After I get the data I don't want to save that data into a file on the server and then give that file for download but just pass that data over ServletOutputStream and allow user to copy that data in a file on client machine.

I wrote a sample program
response.setHeader("Content-Type", "application/comma-separated-values; charset=ISO-8859-1");
response.setHeader("Content-Disposition","attachment;filename=Extract.txt");

ServletOutputStream stream = response.getOutputStream();
String str ="hello world";
byte[] buffer = new byte[str.length()];
buffer = str.getBytes();
stream.write(buffer, 0, str.length());
stream.flush();
stream.close();

with this I am able to open a save/open dialog box onto the broswer and able to save the text in a file but along with the text some exception is also being written into the file.
-------------------------------------------------------------------------
Output:
hello world<PRE>java.lang.IllegalStateException: Response has already been committed
<br>at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.EvermindHttpServletResponse.resetBuffer(EvermindHttpServletResponse.java:1901)
<br>at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.ServletRequestDispatcher.forward(ServletRequestDispatcher.java:211)
<br>at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1069)
<br>at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:455)
<br>at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:279)
<br>at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
<br>at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:507)
<br>at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
<br>at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
<br>at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:765)
<br>at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:317)
<br>at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:790)
<br>at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.AJPRequestHandler.run(AJPRequestHandler.java:208)
<br>at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.AJPRequestHandler.run(AJPRequestHandler.java:125)
<br>at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
<br>at java.lang.Thread.run(Thread.java:534)
<br></PRE></BODY></HTML>
----------------------------------------------------------------------------

I would appreciate if you help me in getting rid of that extra information.

Thank you
Saritha
[ September 10, 2004: Message edited by: Saritha ventrapragada ]
Siva Vu
Greenhorn

Joined: Sep 01, 2004
Posts: 22
Hi Julia,

Thank you for your input,
still even after changing and playing a little bit with repositioning
of the setHeader lines, the problem persists. The only solution I found
so far is ,shut down the browser and restart the browser, then only
the browser is not asking to store the file or writing the cached results directly in the browser.

Is there any solution, without closing the browser that will prevent the writing or prompting to save the cached results when user cancelled the prompted dialog box?

Thank you
Siva Vu
Greenhorn

Joined: Sep 01, 2004
Posts: 22
Any ideas on this problem?
Ajith Anand
Ranch Hand

Joined: Aug 30, 2004
Posts: 40
REF 1:
response.setHeader("Content-Type", "application/comma-seperated-values; charset=ISO-8859-1");
REF 2: response.setHeader("Content-Disposition","attachement;filename=" + filename );



The problem you are facing could be fixed by taking one of the following measures :

In your case, by default, comma-seperated-values are getting associated with IE, maybe because the filename has a known extension : something like .txt or .csv etc. Further these extensions are associated with IE or one of its pluggins.



Solution 1. In windows machines you can configure the file-extensions to Program-associations, by opening the folder options in the control panel.
Here in the control panel , if you are dealing with .txt files goto filetypes tab, choose .txt extensions from the list, and select advanced options, in the dialog, configure open file to "confirm open after download"


But the drawback of this approach is that if you are deploying this thru IE , you cannot go to each and every user and configure their browsers, which leads us to another proposition....



Solution 2. A Hacked Solution - add "xxx" to the file name as below.

REF 2: response.setHeader("Content-Disposition","attachement;filename=" + filename+"XXX" );
This would definitely bring the file save dialog , for IE wouldnt know how to deal with ".txtxxx files.


LXI Technologies P Ltd
[url]www.lxisoft.com[/url]
 
 
subject: Downloading file through Servlet.
 
Similar Threads
Display PDF in IE from byte array using Servlet
error locating file in servlet
File Download in Servlets
JMF Problems with cut.java sample
Download files from JSP