Downloading during JSP

Hi all,
I have encountered a problem... I have used response.setContentType to download type and also the response header... The download window did pop out and is able to download and it will update my database...
else if (formType.equals("downloadArticle")) {
File file = new File("c:/tmp/test.txt");
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(file);
byte[] buf = new byte[1024];
while (fis.read(buf) != -1)
os.write(buf);
os.flush();
os.close();
fis.close();
// method to remove the file from database
but is it possible that when the download window pop out and I click "cancel".. it will not update my database..

hmm.... thx for ur help... =)
but... are there anywhere that I can do to make it instead of the method above, such that only the client have already downloaded the file then i can delete it from the db?
Message was edited by:
blackb0x

Similar Messages

  • [b]Error during JSP page processing[/b]

    hi , i'm mech.
    i have some probs with jsp. i am trying to connect jsp page with database and printing the data on the browser page. i have created DSN mm using microsoft odbc for oracle and oracle9i's driver oracle in orahome90 but it is giving yet . i have this coding and error.
    ------------------------jsp code--------------------------
    package pagecompile.jsp;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.jsp.*;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.io.FileInputStream;
    import java.io.ObjectInputStream;
    import java.util.Vector;
    import com.sun.server.http.pagecompile.jsp.runtime.*;
    import java.beans.*;
    import com.sun.server.http.pagecompile.jsp.JspException;
    import java.sql.*;
    public class _Connect extends HttpJspBase {
    static char[][] jspxhtml_data = null;
    public _Connect( ) {
    private static boolean jspxinited = false;
    public final void jspxinit() throws JspException {
    ObjectInputStream oin = null;
    int numStrings = 0;
    try {
    FileInputStream fin = new FileInputStream("E:\\JavaWebServer2.0\\tmpdir\\default\\pagecompile\\jsp\\pagecompile.jspConnect.dat");
    oin = new ObjectInputStream(fin);
    jspxhtml_data = (char[][]) oin.readObject();
    } catch (Exception ex) {
    throw new JspException("Unable to open data file");
    } finally {
    if (oin != null)
    try { oin.close(); } catch (IOException ignore) { }
    public void _jspService(HttpServletRequest request, HttpServletResponse  response)
    throws IOException, ServletException {
    boolean jspxcleared_due_to_forward = false;
    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    String _value = null;
    try {
    if (_jspx_inited == false) {
    jspxinit();
    jspxinited = true;
    _jspxFactory = JspFactory.getDefaultFactory();
    response.setContentType("text/html");
    pageContext = _jspxFactory.getPageContext(this, request, response,
                   "", true, 8192, true);
    application = pageContext.getServletContext();
    config = pageContext.getServletConfig();
    session = pageContext.getSession();
    out = pageContext.getOut();
    out.print(_jspx_html_data[0]);
    out.print(_jspx_html_data[1]);
    // begin [file="E:\\JavaWebServer2.0\\public_html\\Connect.jsp";from=(14,2);to=(28,2)]
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection myconn=DriverManager.getConnection("Jdbc:Odbc:mm","madhulika","madhulika");
    Statement stmt = myconn.createStatement();
    ResultSet myResultSet = stmt.executeQuery("Select * from peopletable");
    if(myResultSet != null)
         while(myResultSet.next())
              int eid=myResultSet.getInt("id");
              String fname=myResultSet.getString("firstname");
              String lname=myResultSet.getString("lastname");
              String mail=myResultSet.getString("email");
    // end
    out.print(_jspx_html_data[2]);
    // begin [file="E:\\JavaWebServer2.0\\public_html\\Connect.jsp";from=(30,10);to=(30,13)]
    out.print(eid);
    // end
    out.print(_jspx_html_data[3]);
    // begin [file="E:\\JavaWebServer2.0\\public_html\\Connect.jsp";from=(31,10);to=(31,15)]
    out.print(fname);
    // end
    out.print(_jspx_html_data[4]);
    // begin [file="E:\\JavaWebServer2.0\\public_html\\Connect.jsp";from=(32,10);to=(32,15)]
    out.print(lname);
    // end
    out.print(_jspx_html_data[5]);
    // begin [file="E:\\JavaWebServer2.0\\public_html\\Connect.jsp";from=(33,10);to=(33,14)]
    out.print(mail);
    // end
    out.print(_jspx_html_data[6]);
    // begin [file="E:\\JavaWebServer2.0\\public_html\\Connect.jsp";from=(37,5);to=(43,0)]
    stmt.close();
    myconn.close();
    // end
    out.print(_jspx_html_data[7]);
    } catch (Throwable t) {
    if (out.getBufferSize() != 0)
    out.clear();
    throw new JspException("Unknown exception: ", t);
    } finally {
    if (!_jspx_cleared_due_to_forward)
    out.flush();
    _jspxFactory.releasePageContext(pageContext);
    -------------------error in browser----------------------
    Error during JSP page processing
    java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
         at java.lang.Throwable.(Compiled Code)
         at java.lang.Exception.(Compiled Code)
         at java.sql.SQLException.(SQLException.java:43)
         at sun.jdbc.odbc.JdbcOdbc.createSQLException(Compiled Code)
         at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:3814)
         at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(JdbcOdbc.java:1029)
         at sun.jdbc.odbc.JdbcOdbcConnection.initialize(JdbcOdbcConnection.java:145)
         at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:165)
         at java.sql.DriverManager.getConnection(Compiled Code)
         at java.sql.DriverManager.getConnection(DriverManager.java:126)
         at pagecompile.jsp._Connect._jspService(Compiled Code)
         at com.sun.server.http.pagecompile.jsp.runtime.HttpJspBase.service(HttpJspBase.java:87)
         at javax.servlet.http.HttpServlet.service(Compiled Code)
         at com.sun.server.http.pagecompile.jsp.runtime.JspServlet.runServlet(JspServlet.java:469)
         at com.sun.server.http.pagecompile.jsp.runtime.JspServlet.processJspPage(JspServlet.java:259)
         at com.sun.server.http.pagecompile.jsp.runtime.JspServlet.service(JspServlet.java:97)
         at javax.servlet.http.HttpServlet.service(Compiled Code)
         at com.sun.server.ServletState.callService(ServletState.java:226)
         at com.sun.server.ServletManager.callServletService(ServletManager.java:936)
         at com.sun.server.ProcessingState.invokeTargetServlet(ProcessingState.java:423)
         at com.sun.server.http.HttpProcessingState.execute(HttpProcessingState.java:79)
         at com.sun.server.http.stages.Runner.process(Runner.java:79)
         at com.sun.server.ProcessingSupport.process(Compiled Code)
         at com.sun.server.Service.process(Service.java:204)
         at com.sun.server.http.HttpServiceHandler.handleRequest(HttpServiceHandler.java:374)
         at com.sun.server.http.HttpServiceHandler.handleRequest(Compiled Code)
         at com.sun.server.HandlerThread.run(Compiled

    Backing up a moment, is there a particular reason that you're using the JDBC-ODBC bridge rather than using the Oracle JDBC driver?
    Have you taken a look at the JSP sample code available on OTN? I would start by making sure you can run that.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Windows 8.1 apps downloaded during developer preview install in Chinese on RTM (MS requsted I post this here for script to fix this)

    Hello
    Ever since updating to the RTM version of Windows 8.1 on every PC I have updated and signed into using my Microsoft account whenever I try to install any 8.1 app I installed onto the developer preview version it will always install in Chinese which makes
    using the app impossible for me.
    This happens on all PCs I have updated/used including:
    Surface RT (Windows 8.1 RT)
    Surface 2 (Windows 8.1 RT)
    Dell OptiPlex 990 (Windows 8.1 Pro)
    Dell OptiPlex 790 (Windows 8.1 Pro)
    Sony Tap 20" (Windows 8.1 Pro)
    The language settings of the Microsoft store and all the computers are all set to UK English and as soon as I do a fresh install of the UK version of Windows 8.1 and sign into my Microsoft account then certain apps will always install in Chinese (when in
    the store it says you already own this app and can install it on this PC - when I do it is in Chinese. When the app has not been installed before or was not installed when I had the developer preview then it will install in English).
    This has been driving me mad for months and I previously posted this question back in October in the Office 2013 forums as I first noticed the issue with the OneNote app but it was never resolved:
    http://social.technet.microsoft.com/Forums/office/en-US/448670ae-4494-4a55-8cee-d9f1c9873db7/onenote-windows-81-app-changed-to-chinese-and-cannot-work-out-how-to-change-to-english?forum=officeitpro#448670ae-4494-4a55-8cee-d9f1c9873db7
    I then posted it a few days ago here:
    http://answers.microsoft.com/en-us/windows/forum/windows8_1-windows_store/windows-81-apps-downloaded-during-developer/5dcd0df7-edfe-420e-8737-6a48922969e1
    I have now been asked by a Microsoft Support engineer to post the question here as they said a script can be provided which I can use to fix this.
    I think I just need to clear the fact that I have previously installed these apps as maybe some bug in the developer preview set them to Chinese and it seems to remember this setting. I cannot understand any Chinese so this makes these apps unusable.
    The only other option I can think of is to create a new Microsoft account but I would rather not have to do this.
    Some of the apps affected include the OneNote app and the HP scanner app. I have uninstalled most others and found alternatives.
    Thanks
    Robin
    Robin Wilson

    Hello jrv
    I managed to run the script but cannot really see how it is any different to uninstalling the apps in the normal way except for the fact that you can uninstall multiple apps at once.
    This exact same problem happens on a surface 1, a surface 2 and multiple machines running either Pro or Enterprise. It is not one machine but every machine running 8.1.
    I have not upgraded from the Developer Preview version on any of my machines and always do a fresh install but what I am saying is that I did use the same Microsoft account during that time and it seems to have some record of the apps I installed at that
    time and thinks I want them installed now in Chinese.
    The only thing in common on the 7 machines I have tried (including the 2 surfaces) is that I have joined them to my Microsoft account and the problem seems to be with the Microsoft account and not with all the machines.
    To replicate this I can go to any Windows 8.1 machine and join it to my Microsoft account and this will put certain apps from the store into Chinese and I can find no way to stop this. I am pretty confident that the issue is with the Microsoft account or
    a setting that is synchronising from there.
    The workaround is to sign into a different Microsoft account and this installs them correctly on the same machine.
    I would appreciate any help with clearing out my history of installed apps without having to create a new Microsoft account.
    Thanks
    Robin
    Robin Wilson

  • I have downloaded an album from itunes using HughesNet Download Manager scheduled to download during the 2 am to 8 am download period.  The album seems to have downloaded to my computer.  I found the file in c:\downloads\.   I cannot get it into itunes.

    I have downloaded an album from itunes using HughesNet Download Manager scheduled to download during the 2 am to 8 am download period.  The album seems to have downloaded to my computer.  I found the file in c:\downloads\.   I cannot get it into itunes.   Can anyone please give me step-by-step instructions on how to use the downloaded file?   I have tried to import it and drag and drop.   PLEASE HELP.   Thank you.

    See my response to your other post.

  • Java.lang.OutOfMemoryException during JSP compilation

    Hi,
              hunting down a problem at our customer's site, I upgraded our test server to WebLogic 8.1SP6 from SP5, just on the hunch this might have influenced the problem. What I ended up doing was a complete wipe of our SP5 installation and making a fresh SP6 setup.
              That was a very interesting experience. Lot's of changes. APP-INF/lib working, Windows service creation working. Interesting.
              However, the application failed a few pages inwards with an OutOfMemoryException during JSP compilation. I upped the JVM's memory with -Xms and -Xmx, but it still fails. It didn't with SP5, with all settings at their defaults.
              Anybody an idea?
              Bert Laverman
              Perot Systems Nederland BV
              <pre>javax.servlet.ServletException: JSP compilation of /SomeJSPFile.jsp failed: weblogic.utils.compiler.CodeGenerationException: Exception: 'java.lang.OutOfMemoryError' while trying to invoke: serviceMethod at line 46 - with nested exception:
              [weblogic.utils.compiler.CodeGenerationException: Exception: 'java.lang.OutOfMemoryError' while trying to invoke: serviceMethod at line 46 - with nested exception:
              [java.lang.reflect.InvocationTargetException - with target exception:
              [java.lang.OutOfMemoryError]]]
                   at weblogic.servlet.jsp.JspStub.prepareServlet(JspStub.java:256)
                   at weblogic.servlet.jsp.JspStub.prepareServlet(JspStub.java:196)
                   at weblogic.servlet.internal.ServletStubImpl.getServlet(ServletStubImpl.java:598)
                   at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:406)
                   at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:526)
                   at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:28)
                   at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:27)
                   at com.company.application.impl.TransactionInViewFilter.doFilter(TransactionInViewFilter.java:89)
                   at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:27)
                   at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:7053)
                   at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
                   at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
                   at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3902)
                   at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2773)
                   at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:224)
                   at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:183)
              </pre>

    How did you resolve this problem? I got same error          > ever since upgraded server from sp5 to sp6. Thanks in
              > advance.
              The thing I found is that the startWebLogic.cmd and startManagedWebLogic.cmd scripts (which is where I did the memory settings) are not used at all if you're using managed servers. If you want to adjust memory, it has to be through the settings for that server in the WebLogic console, which is a pain, because you cannot enter one field and have WLS provide defaults for the rest. It's a all-or-nothing. When I finally got them right the managed server process correctly used the new settings and the problem disappeared.
              Cheers,
              Bert

  • I "sent as gift" two songs to a friend. She can't find them. Are they sent to her in an email? Will they download during a sync? How can we recover the songs and get them to her iPhone?

    I "sent as gift" two songs to a friend. She can't find them. Are they sent to her in an email? Will they download during a sync? How can we recover the songs and get them to her iPhone?

    Try going to iTunes Store from the left column, then Account, then Purchase History, then Manage Gifts.

  • Heavy Downloading during off peak hours?

    Hi there,
    I have been doing a lot of reading around the various limits 100GB and 300GB and how they have now been removed by BT, but that everything is now unlimited subject to FUP.
    However, I can't seem to find the answer to my question.
    I would appreciate anyone who is currently in the same position to give me some info.
    If I am a heavy user/downloader, who only mainly use Infinity to download during off-peak hours (usually overnight) will I get throttled during those times (overnight - say for example midnight to 8am)?
    This will be either P2P/Torrents or Usenet (or both), could be maybe 1TB a month or maybe more.
    I am not concerned about normal daytime usage which will probably just be for browsing/emails, not overly heavy usage I don't think.
    Thanks.

    ufo wrote:
    Hi there,
    I have been doing a lot of reading around the various limits 100GB and 300GB and how they have now been removed by BT, but that everything is now unlimited subject to FUP.
    However, I can't seem to find the answer to my question.
    I would appreciate anyone who is currently in the same position to give me some info.
    If I am a heavy user/downloader, who only mainly use Infinity to download during off-peak hours (usually overnight) will I get throttled during those times (overnight - say for example midnight to 8am)?
    This will be either P2P/Torrents or Usenet (or both), could be maybe 1TB a month or maybe more.
    I am not concerned about normal daytime usage which will probably just be for browsing/emails, not overly heavy usage I don't think.
    Thanks.
    Wow!!! 1TB a month , do you get much sleep
    Usenet is not throttled but P2P is throttled during peak hours. As you are talking after midnight, the throttling should not effect you, but there have been posts saying that the throttling has gone on longer.
    Here is a link to the Broadband usage Policy
    toekneem
    http://www.no2nuisancecalls.net
    (EASBF)

  • Filename on file download from jsp

     

    This may help:
              ----- Original Message -----
              From: "Erik Lindquist" <[email protected]>
              Newsgroups: weblogic.developer.interest.jsp
              Sent: Wednesday, June 28, 2000 6:20 PM
              Subject: How to dynamically display images in JSPs
              > This took a little while to figure out so I thought I'd share. After
              > doing some research I was led to the following approach on how to load
              > images from an Oracle database into a JSP:
              >
              > The "main" JSP:
              >
              > <HTML>
              > <head>
              > <title>Image Test</title>
              > </head>
              > <body>
              > <center>
              > hello
              > <P>
              > <img border=0 src="getImage.jsp?filename=2cents.GIF">
              > <P>
              > <img border=0 src="getImage.jsp?filename=dollar.gif">
              > <P>
              > world
              > </body>
              > </HTML>
              >
              >
              > And this is the image getter:
              >
              > <% try {
              > response.setContentType("image/gif");
              > String filename = (String) request.getParameter("filename");
              > java.sql.Connection conn =
              > java.sql.DriverManager.getConnection("jdbc:weblogic:pool:orapool"); //
              > connect to db
              > java.sql.Statement stmt = conn.createStatement();
              > String sql = "select image from testimage where filename = '" +
              > filename + "'";
              > java.sql.ResultSet rs = stmt.executeQuery(sql);
              > if (rs.next()) {
              > byte [] image = rs.getBytes(1);
              > java.io.OutputStream os = response.getOutputStream();
              > os.write(image);
              > os.flush();
              > os.close();
              > }
              > conn.close();
              > }
              > catch (Exception x) { System.out.println(x); }
              > %>
              >
              >
              > The thing to note is that there are no <%@ page import="..." %> or <%@
              > page contentType="..." %> tags - just the single scriptlet. It
              > seems that for every "<%@" the weblogic compiler sees it puts
              > out.print("\r\n"); statements in the generated java source.(???) I
              > don't know much about how browsers work but I think that once it sees
              > flat ascii come at it it treats everything that follows as text/plain
              > which is incorrect for the binary stream that's being sent. Another
              > work around was to set out = null; but that's kind of ugly and might
              > produce server errors. The real fix is to write a bean to handle images
              > which I'll work on next (does anybody have any hints on how to do
              > that?)
              Cameron Purdy
              [email protected]
              http://www.tangosol.com
              WebLogic Consulting Available
              "Ramesh" <[email protected]> wrote in message
              news:[email protected]...
              >
              > Hi,
              >
              > Even I could download the files with this technique, I couldn't open the
              file downloaded. It seems the file is getting currepted during tranfer.. Can
              u help me in this regard please?
              >
              > Thank u
              > Ramesh
              >
              > [email protected] (Anders B. Jensen) wrote:
              > >In an Web-application written in Java Server Pages it should be possible
              > >for the user to download data from the web-server. The data will never
              > >exist as a file on the web-server, only in the PrintWriter object, out.
              > >To force the Internet Explorer (IE) to show the download dialog window
              > >the Contenttype of the HTTP-header have been set to "html/transfer". The
              > >question is:
              > >
              > >Is it possible to set the filename appearing in the download dialog
              > >appearing on the client?
              > >
              > >
              > >Below is a listing of the source-code:
              > >
              > ><%@ page extends="com.beasys.portal.admin.PortalJspBase"%>
              > ><jsp:useBean id="download" scope="session" class="dk.lec.DownloadData" />
              > >
              > ><%
              > > String tmpstr;
              > > response.setContentType("html/transfer");
              > > out.clear();
              > > tmpstr=download.getStrbuffer().toString();
              > > out.println(tmpstr.trim());
              > >%>
              > >
              > >
              > >Anders B. Jensen
              > >Consultant, Research & Development
              > >LEC AS
              > >
              > >Remove the SPAMLESS to mail me.
              >
              

  • Problem with file download through JSP under WLS6.1 SP3

    Hello,
    We're in the process of trying to migrate from WLS 6.1 SP1 to SP3, and we're encountering
    some difficulties with this migration.
    I'm attaching a very simple JSP here - it's a snippet from a larger more dynamic
    JSP, that I managed to narrow down to a pretty simple case which still doesn't
    work.
    This JSP opens a file residing at "c:\\BDELog.txt" (it's hardcoded - so change
    it to any textual local file on your machine in order to test it), and writes
    it to the output stream as a txt attachment.
    This JSP works perfectly well on SP1, however, on SP3, it fails only during the
    first hit. If you call this JSP again from the same browser window - it'll work.
    Needless to say - this isn't an acceptable behavior for a website.
    Hope you can help.
    Appreciate any response.
    Roy.
    [download.jsp]

    SP4 indeed solved it.
    Thanks again!
    Roy.
    "Eric Gross" <[email protected]> wrote:
    As a follow-up, SP4 is now available.
    Regards,
    Eric
    "Eric Gross" <[email protected]> wrote in message
    news:3dd19974$[email protected]..
    I would wait until SP4(I believe it may be coming out this week actually).
    If you can't wait until then, please contact support for a 1-off patch.
    Regards,
    Eric
    "Roy Abitbol" <[email protected]> wrote in message
    news:3dd10ef1$[email protected]..
    Many thanks !! (sigh of relief...)
    Is there a way to work around this problem - for example - write
    the
    header explicitly
    so that the problematic header will be overriden or simply get a
    patch
    from you
    guys ?
    Or do we have to wait for SP4 ?
    Thanks again,
    Roy.
    "Eric Gross" <[email protected]> wrote:
    This is a known issue and has been fixed.
    The fix is in SP4. This has to do with a bug that IE has with respect
    to a
    header:
    Cache-Control: no-cache="set-cookie"
    We introduced that as the default header to be returned on all
    responses.
    As of SP4(due out very soon), the default behaviour will be notto send
    this
    header back with each response.
    Regards,
    Eric
    "Roy Abitbol" <[email protected]> wrote in message
    news:3dca7f19$[email protected]..
    Hello,
    We're in the process of trying to migrate from WLS 6.1 SP1 to
    SP3,
    and
    we're encountering
    some difficulties with this migration.
    I'm attaching a very simple JSP here - it's a snippet from a largermore
    dynamic
    JSP, that I managed to narrow down to a pretty simple case which
    still
    doesn't
    work.
    This JSP opens a file residing at "c:\\BDELog.txt" (it's hardcoded- so
    change
    it to any textual local file on your machine in order to test
    it),
    and
    writes
    it to the output stream as a txt attachment.
    This JSP works perfectly well on SP1, however, on SP3, it fails
    only
    during the
    first hit. If you call this JSP again from the same browser window- it'll
    work.
    Needless to say - this isn't an acceptable behavior for a website.
    Hope you can help.
    Appreciate any response.
    Roy.

  • File Download in JSP, Please help

    I am wondering if somebody can help me with a problem :
    I am trying to register a fact that somebody has downloaded a file
    from my company's website.
    When a user clicks on the link I provided, a message box came up to prompt user with the location to save the file. How can I register the fact that user press "Cancel" instead of OK. In other words I need to be able to tell whether the guy really downloaded it or not.
    Thanks

    So, how to determine if user had pressed 'Cancel' or just the connection is broken?
    The pure JSP cannot do it.
    I think you should have some binary code like applet or active-x to check it.

  • File download using jsp

    I am trying to download a file from the server using jsp but it always shows the file in the browser.I want a Save/Open dialog box to allow the user to save this file in the local system. any feedback is welcome.
    thanks in advance
    vinod

    Basically out frame work is in struts.........
    In struts for file down load I wrote the code as
    String fileName = <file name>;
    String filePath = <file path>;
    String fileType = fileName.substring(dotIndex+1,fileName.length());
    ServletOutputStream out = httpservletresponse.getOutputStream();
    if (fileType.trim().equalsIgnoreCase("doc"))
    httpservletresponse.setContentType( "application/msword" );
    else if (fileType.trim().equalsIgnoreCase("xls"))
    httpservletresponse.setContentType( "application/vnd.ms-excel" );
    else if (fileType.trim().equalsIgnoreCase("pdf"))
    httpservletresponse.setContentType( "application/pdf" );
    else if (fileType.trim().equalsIgnoreCase("ppt"))
    httpservletresponse.setContentType( "application/ppt" );
    else
    httpservletresponse.setContentType( "application/octet-stream" );
    httpservletresponse.setHeader("Content-disposition", "attachment; filename=" +actualName );
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
    BufferedOutputStream bos = new BufferedOutputStream(out);
    byte[] buff = new byte[2048];
    int bytesRead;
    while(-1 != (bytesRead = bis.read(buff, 0, buff.length)))
    bos.write(buff, 0, bytesRead);
    I hav written this in seperate function which returns boolean true If this works correctly otherwise fase.
    If it is 'true ' I am forwarding it to 'success.jsp' else'fail.jsp'....................
    Now problem is It is not forwarding to any other pages and giving error as "Illegal state .can not forward.Response already committed."
    I think this error is coming becos of 'response.setHeader()' and using out object.........
    Please give me any solution for this problem.........Since I am strucked here.It is urgent for me to do...................................
    I don't mind If u giv any alteernative code for this..............
    Thanx in advance..................
    Plz. respond quickly...................

  • Download from jsp----

    hi friends!
    i am using a jsp for a download of a video file.The download step should be like,
    clicking the right mouse button on the link and select,'save target as' to save the file into the computer hard disk.
    Here is the place where i have been wall-blocked to proceed further.That is i have to track the user that he clicked and downloaded the specific file.The user i mean is a memeber who logs in and reaches upto the download page.
    This tracking is necessary in order that the total file size downloaded for the 24 hours duration does not exceed 1.2GB.If it exceeds when the user clicks one clip he will be served with the message to relog in after 24 hours for further downloads
    I am really stuck as how to implement this in the site.I am coming in the second round to the forum,seeking advise/solution to this task.Now i have to launch the site in a weeks time.
    Help me please.The implementation of this tracking process is crucial to satisfy the client.
    thanks and regards
    sat

    hi leo_pruna
    If your referring to right clicking that can be done anywhere regardless of what country you are in. What you need to do is create a servlet that controls the downloads. If a user right clicks and saves target as and doesn't have rights to download the video then the servlet should forward to an html (JSP) page. At that point if they just saved target as then they should only get the HTML representation and not the video.
    Thanks a lot.I really did not understand what u are telling me to do in the above paragraph.
    According to my cient demand , the video download is allowed for members only.
    To achieve this, i have done the implementation as follows:
    After the user logs in,
    When he wants to download a movie he will go to the downloadjsp, where the movie is split into many parts and each part has download link displayed .
    When he clicks one of the links, he will be allowed to download through download servlet and the download servlet will ensure his limit and acts accordingly.
    The above operation is performed through a left click of mouse button on the download link of download jsp.
    but in japan for the video download sites, the download is allowed only by rt clicking and selecting save targer as option.This is as per the law of the country.
    what i planned to do now in order that the rt click download opration to be effective is, just let the user to download from the download jsp itself, without going to the download servlet.(this effectively renders me the download without user tracking)
    I did not got idea as how to incorporate the servlet way of downloading by rt clicking on the link .that is the reason i have planned to do so.
    And now that u have suggested me some solution which will also enable me to track the users through the rt click action with download servlet.The above highlighted part(***) from your reply i can not follow.pl pardon me for saying that.
    If u explain to me again the same , i will be able to implement.
    will u take pains to explain again
    thanks and regards
    sat

  • How to make file download in JSP ?

    Friends,
    i am using following code :
    // LISTING FILES IN DIR
            out.println("<br>");
            File dir = new File(dirName);
            String[] children = dir.list();
                 if (children == null)
            // Either dir does not exist or is not a directory
                 else
                    %>
                    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="68%" id="AutoNumber1">
                    <tr>
                        <td width="50%" align="center"><font face="Verdana">File</font></td>
                        <td width="50%" align="center"><font face="Verdana">Action</font></td>
                          </tr>   
                        <%
                        for (int i=0; i<children.length; i++)
                        // Get filename of file or directory
                        String filename = children;
    //out.println(filename);
    %>
    <tr>
    <td width="50%">
    <p align="center"><font face="Verdana"><%=filename %></font></td>
    <td width="50%">
    <p align="center"><font face="Verdana"><a href="<%= children[i %">">View</a></font></td>
    </tr>
    <%
    out.println("<br>");
    %>
    SInce i am not able to download file from link.
    link shows path correct but why its not working ??
    HELP ME.
    *i don't want to show real path( physical location of file) on file donwload link.*
    Example :
    *it will not allow to show like following :*
    *C:\project\webUpload\build\web\fuploads\file2.jpg*
    *it may allow like :*
    *\webUpload\fuploads\file2.jpg*
    Thanks</a>

    My friend you are getting it all wrong here...
    Here we would be taking help of a dedicated servlet to locate and download a file(which would be the output the respective concent of depeding of the fineName or fileId you send in).
    Please find some time and try to consider the below case...
    Say i have a Servlet which takes a Request of detailed filePath and would give output as file itself....
    and you prompt you give a link to that servlet from you JSP to download that file...
    Checkout the below Code snippets to get some idea
    DownloadPrompting.JSP:
    ==================
    <a href="FileServlet?fileName=C:\fileuploaded\image1.jpg" title="C:\fileuploaded\image1.jpg">Click Here to download Image1 JPEG File</a>
    <c:forEach var="fileName" items="${sessionScope.fileNames}">
       <a href="FileServlet?fileName=<c:uri value="${fileName}"/>" title="<c:out value="${fileName}"/>">Click Here to download</a>
    </c:forEach>
    -------------------------------------------------------------------------FileServlet.java
    ===========
    package com;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URLConnection
    public class FileServlet extends HttpServlet{
      private void processAction(HttpServletRequest request,HttpServletResponse response) throws Exception{
           // getting fileName which user is requesting for
           String fileName = request.getParameter("fileName").replace('\\','/');
           boolean exists = new File(fileName).exists();
           // Checking whether the file Exists or not      
           if(exists){
            FileInputStream input = null;
            BufferedOutputStream output = null; 
            int contentLength = 0;
            try{
                // Getting the Mime-Type
                String contentType = URLConnection.guessContentTypeFromName(fileName); 
                if(contentType == null)        
                   contentType = "application/octet-stream";
                input = new FileInputStream(fileName);
                contentLength = input.available();
                // Enables us to specify of what kind of content we are trying to download.
                response.setContentType(contentType);
                // Specifes How much amountof data we straming & trying to download
                response.setContentLength(contentLength);
                // Adding Content Disposition header so that it cud enable us to get OPEN/SAVE  after clicking on the link 
                response.setHeader("Content-Disposition","attachment;filename="+fileName+"\");
                // Initializing File Streaming Response via a Servlet
                output = new BufferedOutputStream(response.getOutputStream());
                // Placing each byte on to the stream after reading it from the file
                while ( contentLength-- > 0 ) {
                   output.write(input.read());
                 // Flushing the stream.         
                 output.flush();
              }catch(IOException e) {
                     System.err.println("Exception Occured:"+e.getMessage());
                 System.err.println("Exception Localized Message:"+e.getLocalizedMessage());
              } finally {
                   // Closing the INPUT stream 
                   if (input != null) {
                       try {
                          input.close();
                      } catch (IOException ie) {
                          System.err.println("Exception Occured:"+e.getMessage());
                             System.err.println("Exception Localized Message:"+e.getLocalizedMessage());                      
                   // Closing the OUTPUT stream 
                   if (output != null) {
                       try {
                          output.close();
                      } catch (IOException ie) {
                          System.err.println("Exception Occured:"+e.getMessage());
                             System.err.println("Exception Localized Message:"+e.getLocalizedMessage());                      
           }else{
             response.sendRedirect("/errorPage.html");
      public void doPost(HttpServletRequest request,HttpServletResponse response) throws Exception{       
            processAction(request,response); 
      public void doGet(HttpServletRequest request,HttpServletResponse response) throws Exception{
            processAction(request,response); 
    }And if you are thinking of hiding filepath & all...
    Here is a hint for you...
    Try to maintain a properties file which has a key value pairs of that something like.
    112345678=C:\\uploadfile\\image1.jpg
    122142637=C:\\uploadfile\\image2.jpg
    or create a Database table which which an autogenerated primany key with some Id and holds the complete filePath.
    and in this case you would access the file something like the one below from your jsp
    <a href="FileServlet?fileId=112345678" title="112345678">Click Here to download Image1 JPEG File</a>
    <c:forEach var="fileId" items="${sessionScope.fileNames}">
       <a href="FileServlet?fileId=<c:uri value="${fileId}"/>" title="<c:out value="${fileId}"/>">Click Here to download</a>
    </c:forEach>
    -------------------------------------------------------------------------and in the fileServlet you might have to change the below part to
    // getting fileName which user is requesting for
           String fileName = request.getParameter("fileName").replace('\\','/');to something like
    // getting fileName which user is requesting for
           String fileId = request.getParameter("fileId");
       /*Querying the database or reading the Properties file to findout the correspoding filePath associated with the fileId something like*/
        String fileName = ResourceDelegate.getInstance().getFile("fileId").replace('\\','/');
    NOTE:* The idea is similar to what my fellow poster is trying to explain you in all his posts.
    Hope that might help :)
    REGARDS,
    RaHuL

  • Excel file download in jsp

    Hi,
    Is it possible to download excel file on the server on a JSP page. Kindly advice.
    Thanks in advance.

    yes...
    What is the scenario....
    is it..
    1. You have a XLS on server...alredy created..
    2. Now you need a link on JSP page....that is linked to this EXS file...
    3. User acess your web application and click on link....
    4. A popup comes up....and user selects either to save or download the file....
    Is this your scenario....
    If not then specify steps you are looking for....and you face issue in which step....
    Edited by: Saurabh Agarwal on Jul 6, 2011 12:21 PM

  • Can any body give me code for file download in jsp

    Hi all,
    I have done file uploading to a particular dir C;\uploadfiles, and store the name of the file with other information in a table. Now I want to download that file of any format from that dir using jsp or servlet.
    Can anybody please help me with some code.
    Thanks and Regards
    Rajib

    This seems more like a job to a servlet
    public String getContentType(){
      this should return the cntent yupe of the file
      that shoule be downloaded
      if unknown use something like binary/data
    public byte[] getFileData(){
    This should return the data of the file as a byte array
    public void doGet(......................){  // or doPost
       res.setCotentType(getContentType());
       OutputStream os = res.getOutputStream();
       os.write(getFileData());
       os.close();
    }Above is the most simplest way to do it
    and havent been tested you might need changes based on your program design

Maybe you are looking for

  • Network issues. Packet loss when spray is used!!!!!!!!!!!!!!!

    Hi, I am not in a position to figure out, is it an issue with my server or my network. I run spray and find packet loss...what should I suspect? In one way, the packet loss is 0%, while the other way, there is 90% loss. Both machines are located in t

  • The attempt to burn a disc failed. An Unknown error occurred

    "The attempt to burn a disc failed. An Unknown error occurred (4450)" This is the error message I get when I try to burn a CD. This PC IS authorized. These files have not been burned before. This is a new Dell Dimension 9100 DVD/RW I've burned CDs su

  • Turn off home sharing on a computer i no longer have

    I have five home sharing set up but i no longer have two of the computers one broke and i sold one is there any way of turning home sharing off on these computers so that i can set it up on my new mac?

  • Error when executing DBMS_ERRLOG through Stored Procedures...

    Hi, We have TWO schemas like IDWH_ODS and IDWH_ERR running on Oracle 10g Rel.2. The schema IDWH_ERR has direct SELECT privilege on all the base tables in IDWH_ODS schema. (As Pl/sql doesn't support ROLE, we have granted direct SELECT on each of the t

  • SAP HR LDAP

    Hi, im looking for a possibility to synchronize the employee data from HR with an directory service. Additionally i want to synchronize the data (like telephone number and adress) from the userstore with the data in HR. The aim is: if you change data