Quick Search for:  in language:    
JSP,article,along,with,code,snippet,illustrat
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
Java/ Javascript Stats

 Code: 220,465. lines
 Jobs: 92. postings

 How to support the site

 
Sponsored by:

 
You are in:
 
Login





Latest Code Ticker for Java/ Javascript.
Click here to see a screenshot of this code!vok - The vocabulary trainer
By Thorsten Stärk on 1/7

(Screen Shot)

Java, Calculator
By Rockwell on 1/4


Eatable Interface
By Rockwell on 1/4


Superclass Person
By Rockwell on 1/4


Draws Cube Function
By Rockwell on 1/4


Rectangle Class
By Rockwell on 1/4


Find Number of Upper and Lower Case Letters in a Command Line Argument String
By Rockwell on 1/4


anagrams
By Rockwell on 1/4


Text Reader with Tokenizer
By Rockwell on 1/4


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!

Affiliate Sites



 
 
   

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

Print
Email
 

Submitted on: 5/17/2001 5:17:57 PM
By: Manjunath P Reddy 
Level: Advanced
User Rating: By 9 Users
Compatibility:Java (JDK 1.1), Java (JDK 1.2)

Users have accessed this article 35609 times.
 
 
     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 + " byt
            //     es 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 3 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
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 AM:Puneet Wadhwa
Hi Manjunath, Your articles are practical and useful. I sure learnt a few new tricks! All the best for the contest :)
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/23/2001 1:13:49 PM:Scott 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: <pre>ServletOutputStream outs = response.getOutputStream();</pre> Just use the standard 'out'. (2) Before doing any write()s, do:<pre> out.clearBuffer();</pre> This gets rid of any odd characters that may already be in the output stream.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/23/2001 1:15:37 PM:Marc 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
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
11/7/2001 8:01:29 PM:Visala 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.IllegalStateExcepti on at allaire.jrun.servlet.JRunResponse.getOut putStream(../servlet/JRunResponse.java:2 94) Thanks Visala
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
11/28/2001 12:12:31 PM:Garrett 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
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/5/2002 4:22:39 PM:Lee 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(
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/5/2002 4:24:08 PM:Lee
I did exactly what you recommended. But there is no Acrobat Reader pop-up. The letter 'W' print within the browser. <% response.setContentTy pe("application/pdf"); response.setHea der ("Content-Disposition", "myfile.pdf"); ServletOutputStream outStream = response.getOutputStream(); try{ outStream.write(87); }catch (Exception e) { } outStream.flush(); outStream.close(); %>
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/18/2002 12:56:36 AM:Rajesh.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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/28/2002 1:45:40 AM:yugandhar
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
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/24/2002 3:45:20 PM:ian
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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/3/2002 8:09:38 AM:Thomas
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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/18/2002 10:28:28 AM:Jonathan 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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/25/2002 8:29:55 AM:vaibhav
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=
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/25/2002 8:33:42 AM:vaibhav
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" --%> <html> <body> <%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(); %>
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/9/2002 3:10:28 PM:Mitchell 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?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
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
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/15/2002 5:18:18 AM:
Hi, The open/save dialog box appears. The dialog box always opens up with the
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
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?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
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?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
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
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
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
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | Java/ Javascript Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.