Important alert: (current site time 9/3/2014 2:39:40 AM EDT)
 

article

How to force -download an attachment/application using JSP.

Email
Submitted on: 5/17/2001 5:17:57 PM
By: Manjunath P Reddy 
Level: Advanced
User Rating: By 11 Users
Compatibility: Java (JDK 1.1), Java (JDK 1.2)
Views: 200812
 
     This article along with the code snippet illustrates how to force download an attachment from the server to clients using JSP.

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				
How to force download of an attachment/application using JSP.

Many of you guys out there would have experienced the problems associated with the browser interpreting whether to download an application/attachment or open up in the same browser instance. Whenever microsoft's IE encounters a href tag pointing to an excel/doc/ppt or any other tool whose plugins have been installed on the client, it opens the attachment in the same instance of the browser. Hence if a user has to save the file then he has to be smart enuff to click on file --> save as from the menu and then save to his hard disk.

But most web-applications are designed for ease and not keeping the user's technical skill or knowledge in view. Hence when a user clicks on a href(which might say click to download pdf version) pointing to say mydownloadable.pdf, what happens is the pdf downloads the file to his temporary internet files and shows it in the browser.

The code snippet below shows how one can force download a file/app/attachment to the user irrespective of whether the user has a necessary plugin or not. Even the name of the downloaded file can be specified dynamically.

<!--contents of download.jsp-->
<%@ page import="java.util.*,java.io.*"%>
<!--Assumes that file name is in the request objects query Parameter -->
<%
	//read the file name.
	
	File f = new File ("c:/fop/mypdf/" + request.getParameter("file") );
	//set the content type(can be excel/word/powerpoint etc..)
	response.setContentType ("application/pdf");
	//set the header and also the Name by which user will be prompted to save
	response.setHeader ("Content-Disposition", "attachment; 				
filename=\"LicenseAgreement.pdf\"");
	
	//get the file name
	String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
	//OPen an input stream to the file and post the file contents thru the 
	//servlet output stream to the client m/c
	
		InputStream in = new FileInputStream(f);
		ServletOutputStream outs = response.getOutputStream();
		
		
		int bit = 256;
		int i = 0;
		try {
			while ((bit) >= 0) {
				bit = in.read();
				outs.write(bit);
			}
			//System.out.println("" +bit);
		} catch (IOException ioe) {
			ioe.printStackTrace(System.out);
		}
//		System.out.println( "\n" + i + " bytes sent.");
//		System.out.println( "\n" + f.length() + " bytes sent.");
		outs.flush();
		outs.close();
		in.close();	
%>

Hope you find this useful...
Adios and Happy Programming!!!
-------------------------------------------------------
Carved upon my stone, My body lies but still I roam...
Manjunath P Reddy


Other 2 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Advanced category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

5/19/2001 9:55:36 AMPuneet Wadhwa

Hi Manjunath,
Your articles are practical and useful. I sure learnt a few new tricks! All the best for the contest :)
(If this comment was disrespectful, please report it.)

 
8/23/2001 1:13:49 PMScott Boone

This will (on the ATG servlet server, if nothing else) sometimes cause a newline to be added as the first byte of the file. To avoid this: (1) Don't bother using outs:
ServletOutputStream outs = response.getOutputStream();
Just use the standard 'out'. (2) Before doing any write()s, do:
out.clearBuffer();
This gets rid of any odd characters that may already be in the output stream.
(If this comment was disrespectful, please report it.)

 
10/23/2001 1:15:37 PMMarc Baker

Manjunath, the code you shared on force downloads of PDFs was very useful. I have a follow-up question if you'd be so kind. I am reading the pdf file from a Blob in Oracle instead of reading it from a file. I can get the pdf to display in Netscape 4.7 but cannot get it to display in IE 5.5 without first changing the File...Prefrences...General (disable Web Browser Integration) setting in Adobe. Do you know of any workarounds for this?

Please respond to mbaker@crowechizek.com. thanks kindly,

Marc
(If this comment was disrespectful, please report it.)

 
11/7/2001 8:01:29 PMVisala Valiveti

This is what exatly i was looking for. It is extreamly useful. I have a question,
when i try to run the code on my machine, i got the below error. Am i missing any classpath or anything else. please suggest.
I am using IIS webserver and Jrun application server.

java.lang.IllegalStateException
at allaire.jrun.servlet.JRunResponse.getOutputStream(../servlet/JRunResponse.java:294)
< BR>Thanks
Visala

(If this comment was disrespectful, please report it.)

 
11/28/2001 12:12:31 PMGarrett Bowhall

I apologize in advance for my lack of knowledge when it comes to JSP, ASP and the like. After reading your article, I don't know where or how to put this code into my web page in which I am trying to force download. If you could give me a little more information as to how to do that, I would appreciate it. Thank you!

garrett@pivotdesign.com
(If this comment was disrespectful, please report it.)

 
3/5/2002 4:22:39 PMLee Jin

I did exactly as you said. My IE (5.50) only shows the character 'W' in the browser, no Acrobat Reader pop-up. Here is the code:

<%

response.setContentType(
(If this comment was disrespectful, please report it.)

 
3/5/2002 4:24:08 PMLee

I did exactly what you recommended. But there is no Acrobat Reader pop-up. The letter 'W' print within the browser.

<%

response.setContentType("application/pdf");
response.setH eader
("Content-Disposition", "myfile.pdf");

ServletOutputStream outStream = response.getOutputStream();

try{
outStream.write(87);
}catch (Exception e) { }

outStream.flush();
outStream.close();

%>
(If this comment was disrespectful, please report it.)

 
3/18/2002 12:56:36 AMRajesh.V

Hi Manjunath,
Ur article was good & it gave me a confidence thatPdf files can be downloaded.I have a problem like..
i have a gif in my webpage.When the user clicks that a .pdf file shud be downloaded from the server.I donot know the server path.when the user cliks the gif he should be promted with the "Save As" dialog box & be able to store the ".Pdf" where he wants to store in his machine.i want the javascript coding which should be emmbedded in Perl.Thanx in advance.
(If this comment was disrespectful, please report it.)

 
3/28/2002 1:45:40 AMyugandhar

hi manjunath,
I want the user to force for download.
I saw ur code and tried to implement it. it is giving some problem. Can u please guide me. It is very important.
It is asking for file download and on clicking on save it is giving Internet Exploreer cannot download download.jsp from localhost. Pls. guide me. My id is yyreddy@sysarris.soft.net
(If this comment was disrespectful, please report it.)

 
5/24/2002 3:45:20 PMian

Thanks for the tip and it is exactly the one i am looking for. I also found that using 'out' is better for ascii data such as text data. You can also created a BufferedReader filter for filereader to readline(). This way, the performance is dramatically increased.


(If this comment was disrespectful, please report it.)

 
6/3/2002 8:09:38 AMThomas

I had a problem with:

setHeader ("Content-Disposition", "attachment; filename=\"LicenseAgreement.pdf\"");

while using it with excel, now I choose addHeader instead, and it works like a charm.
(If this comment was disrespectful, please report it.)

 
6/18/2002 10:28:28 AMJonathan Churchman

Hi, trying to implement what looks a great bit of code, but I'm getting IllegalStateException, which after some digging appears to be because apparently you can't call response.getOutputStream() if a JSPWriter has already called it. Which because I'm using JRun 3.1 the JSP compiler automatically does. Some suggestions please, would be most helpful.
(If this comment was disrespectful, please report it.)

 
6/25/2002 8:29:55 AMvaibhav

below is my code--when i submit this query in excel the form data is not submitted only varaible are submmited .how to write the sql query



<%@page import=
(If this comment was disrespectful, please report it.)

 
6/25/2002 8:33:42 AMvaibhav

below is my code ,when i submit this form in excel the variable name get submmited not the actual value which are placed in html form .please give me the syntax for sql query <%@page import="java.sql.*"%> <%--<%@page contentType="application/excel-document" --%> <%Connection c=null; Statement stmnt =null;%> <% String a1=request.getParameter("name");%> <% String a2=request.getParameter("pass");%> <% Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ); c = DriverManager.getConnection( "jdbc:odbc:try", "", "" ); stmnt = c.createStatement(); String query = "insert into [trytable$] values(a1,a2);";//trytable is name of tab stmnt.executeUpdate( query ); stmnt.close(); c.close(); %>
(If this comment was disrespectful, please report it.)

 
7/9/2002 3:10:28 PMMitchell Gould

I would like to allow users to download a file from a remote site. When I put in the url for the remote site in the File f = new File ("c:/fop/mypdf/" + request.getParameter("file") ); code it does not work. How do I code this?

(If this comment was disrespectful, please report it.)

 
9/10/2002 6:58:37 PM

Hey, that code was way usefull. But i was wondering if you knew how to force an open as opposed to the force download. If you could help me id be very gratefull. Thanks.
(If this comment was disrespectful, please report it.)

 
9/25/2002 8:41:34 AM

Thank you for your contribution . i was trying to use the code to download a file , but i get a messae IE cannot download from local host . how to resolve this . i am new to JSP programming

Thank you
(If this comment was disrespectful, please report it.)

 
10/15/2002 5:18:18 AM

Hi,

The open/save dialog box appears.
The dialog box always opens up with the
(If this comment was disrespectful, please report it.)

 
12/10/2002 7:06:16 AM

Your code is OK on IE, but why Netscape doesn't show me the save-prompt, but it saves the file... I' don't know where?
(If this comment was disrespectful, please report it.)

 
12/10/2002 7:08:27 AM

I use your code and on IE is ok, but why Netscape doesn't show me the save-form but it saves the file... I don't know how?
(If this comment was disrespectful, please report it.)

 
1/16/2003 8:35:59 AM

I have problem with download manager (flashget or netscape smart download): it downloads an EMPTY file, whereas with
(If this comment was disrespectful, please report it.)

 
4/16/2003 11:36:35 AM

I'd like to know if it's possible to know when the download has been finished. I want the user download a file but just once. After the download I want remove it but how can I know that the user hasn't canceled the download ?

thanks
(If this comment was disrespectful, please report it.)

 
7/14/2004 7:01:23 PM

Hi, thanks fpr your article - but is there a way in coding the html file to force the download? The server and the website i use has no jsp.
Many thanks!
(If this comment was disrespectful, please report it.)

 
7/14/2004 7:02:13 PM

Thanks for your article - but is tehre a way to code a forced download right into html/javscript? my server has no jsp support.
(If this comment was disrespectful, please report it.)

 
8/11/2004 12:37:03 PM

<%
File f = new File(
(If this comment was disrespectful, please report it.)

 
8/29/2004 9:19:25 PM

Great script! I'm using it in a business app that writes out database query results to .csv format for use with excel. However, when I download the resulting .csv file I get an unwanted "˙" character @ the end. Any ideas on how to fix this?
(If this comment was disrespectful, please report it.)

 
10/12/2004 4:51:24 PM

hi manjunath, thanks for sharing your code snippet. but i have a question about file download. do you know if there is a way i can retrieve the full path where the file has been downloaded to on the client machine? or is it even possible?? thanks!
(If this comment was disrespectful, please report it.)

 
2/8/2005 4:36:41 AM

Hi. Thanks for this article. Its good. But is it necessary to first have a physical file (say "test.xls")? Can't I create the Excel file on-the-fly using some API (like POI or JExcelAPI), and then download the file to the browser?
(If this comment was disrespectful, please report it.)

 
2/14/2005 2:16:34 PM

Please change this part:

while ((bit) >= 0)
{
bit = in.read();
outs.write(bit);
}


to:

int bit = in.read();
while ((bit) >= 0)
{
outs.write(bit);
bit = in.read();
}

(If this comment was disrespectful, please report it.)

 
2/15/2005 8:20:03 AM

Please change this part: while ((bit) >= 0) { bit = in.read(); outs.write(bit); } to: int bit = in.read(); while ((bit) >= 0) { outs.write(bit); bit = in.read(); }
(If this comment was disrespectful, please report it.)

 
2/23/2005 12:57:04 AM

Hi,
Your code is very good. When i download a file from server to client, the browser asks where to save. After this, i want to process according to the action taken place, ie, whether the client is saving the file or cancelling the save. Can I do that? Can u or anyone help me out in this?
(If this comment was disrespectful, please report it.)

 
3/23/2005 9:42:56 AM

When I download the resulting .csv file I get an unwanted character @ the end and empty new lines in the beginning. Any ideas on how to fix this?
(If this comment was disrespectful, please report it.)

 
3/23/2005 9:44:54 AM

When csv file gets downloaded then some empty new lines get appended in the beginning.Any ideas on how to fix this?
(If this comment was disrespectful, please report it.)

 
4/18/2005 2:57:10 AM

I am trying to write an application which can upload and download files [Excel, Word etc.] to/from an Oracle 9i database Blob field. I am using Java/JSP for the same.
The upload part works just fine. However, when I try to download the file that I uploaded, I get an error.
When I click on the download link, a dialog box comes up asking me to Open/Save the file. However, when I try to save it, it says
“Internet Explorer cannot download …..tion=download&planId= testplan from localhost
Internet Explorer was not able to open this Internet Site. The requested site is either unavailable or cannot be found. Please try again later.”
I am using IE 6.0. I tested the same with Firefox browser and was able to download the file.
Can anyone help?
Unfortunately, the interface here doesn't allow me to enter more than 100 0 characters. Else I could have copied the code and pasted it here.
(If this comment was disrespectful, please report it.)

 
5/5/2005 4:08:23 PM

Manjunath,

Thanks for the solution.
Similarly how will i force the download of an html file. I did the same way using the content type as
(If this comment was disrespectful, please report it.)

 
5/12/2005 11:49:06 PM

Hi Manjunath, thanks for the code. The code works fine when downloading .doc, .xls, .pdf. However, I'm getting an error when I am downloading .ppt (powerpoint) file. I'm getting an HTML Type document. I already set the type to response.setContentType (
(If this comment was disrespectful, please report it.)

 
5/12/2005 11:51:14 PM

Hi Manjunath, thanks for the code. The code works fine when downloading .doc, .xls, .pdf. However, I'm getting an error when I am downloading .ppt (powerpoint) file. I'm getting an HTML Type document. I already set the type to application/vnd.ms-powerpoint. Any suggestion?
(If this comment was disrespectful, please report it.)

 
6/15/2005 8:27:54 PM

I created a JSP page with the following code:
<%
response.setContentType("application/pdf");
response.setHeader("Conten t-Disposition",
"attachment; filename=\"entryform.pdf\"");
%>
and it forces a prompt for opening or saving the pdf file.

If you need to do this more than once then you can make it more generic by passing it some parameters:

<%
String contentType = request.getParameter("cType");
String fileName = request.getParameter("fName");
response.setContentType (contentType);
response.setHeader ("Content-Disposition", "attachment; filename=\""+fileName+"\"");
%>

The href target will then be something like:
"genericPromptPage.jsp?cType=application/pdf&fName=entryform.pdf"


(If this comment was disrespectful, please report it.)

 
3/2/2006 7:53:38 PMaaron

I don't understand where/how to declare the path to the file? I want to point to a file on our webserver...where do I put this info. Sorry for the newbie question. I am able to get this script working, however, everytime I download the file, there is 0 bytes and nothing in the actual file?? Thanks in advance
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.