|
|
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 |
|
|
Your Vote! |
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 :)
|
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.
|
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
|
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
|
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
|
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(
|
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();
%>
|
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.
|
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
|
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.
|
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.
|
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.
|
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=
|
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();
%>
|