I have to give user a download file option. when he clicks: save dialog box has to opened and save the file at given path.
There is a problem with my code:
File fil = new File(file_name); long len = fil.length(); int leng = (int)len; byte fileByte = new byte[leng]; //first read the file on the server, store the contents in a byte array FileInputStream fis = new FileInputStream(fil); fis.read(fileByte); response.setContentLength(leng); response.setHeader("Content-Disposition", "attachment;filename=file_name");
//write the byte array to the o/p stream. response.getOutputStream().write(fileByte); -------------------------------------------------------- I am getting error like: getOutputStream() has already been called for this response.
I think my code won't work for all cases, i need a better solution please.
What Adeel means is that, since you already have the file on your server, why don't you provide a link to that file on your output page? Or don't you want to put it in a publicly accessible place? Streaming files from a JSP is tricky, as you have found, because JSPs may write data to the OutputStream before your code runs. I'd recommened converting the download-JSP into a servlet; that way it's easier to control the OutputStream.
JSPs are designed for formatting text. If you want to stream binary data, you're better off doing it from a servlet.
Any characters outside of the "<%...%>" tags will result in an out.println(..) statement being placed in the generated servlet code - even a new line or other whitespace character. This will class with your own handling of the output stream.
If the file lives within your webapp, the simplest thing to do is provide a link as Adeel has mentioned. If not, put the stream handling code in a servlet. If you would like an example of this, I have one on http://simple.souther.us. Look for SimpleStream.