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...................

Similar Messages

  • File upload and download using jsp/servlets

    How to upload any file to the server using jsp/servlets. . Help me out

    You can also try the Jenkov HTTP Multipart File Upload. It's a servlet filter that is easy to add to your web-project. After adding it, you can access both request parameters and the uploaded files easily. It's more transparent than Apache Commons File Upload. There is sufficient documentation to get you started, and there is a forum if you have any questions.
    Jenkov HTTP Multipart File Upload is available under the Apache license, meaning its free to use.

  • 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

  • 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.
              >
              

  • Accessing BSP File Download using HTTPS URL

    Hi,
    I'm struggling with a problem of downloading a file from a https url. I wrote a BSP App for downloading a file from a unix server.. It works fine when I use a http URL with port 8080 and does not work when I use https.!!
    Example:
    https://comms.gmsanet.co.za/supplier [ download does not work ]
    http://comms.gmsanet.co.za:8080/supplier [ download works ]
    When I try to download using https.. it does not pull the file name and path
    see code  below and suggest me if anything to be chnaged.
    In the Form Initialization method:
    event handler fr data retrieval
    DATA: i_file        type string,
          s_fields      TYPE tihttpnvp,
          s_fields_line TYPE ihttpnvp,
          multipart_form type ref to if_http_entity,
          file_upload    type xstring,
          lv_backend     type string,
          success        type string,
          entity         type ref to if_http_entity,
          file           type xstring,
          content_type   type string,
          content_filename type string,
          content_length type string,
          content_disposition type string,
          num_multiparts type i,
          i              type i value 1,
          doEcho         type string value 'X',
          value          type string,
          filename       type ZFILETAB-fileinfo,
          ext1           type string,
          ext2           type string,
          dsn            type string,
          bptype         like sy-uname,
          itab           TYPE ZFILETAB,
          itab_line      TYPE ZFILETABLINE,
          file_ext       type ZFILETABLINE,
          fileinfo       type c,
          zcount         type i.
        filename = '/NewMessge.doc'.
        content_filename = filename.
    Check the extension and assign the content type
        split filename at '.' into ext1 ext2.
        case ext2.
          when 'zip'.
            content_type = 'application/x-zip-compressed'.
          when 'doc'.
            content_type = 'application/msword'.
          when 'txt'.
            content_type = 'text/plain'.
          when 'ppt' or 'pps'.
            content_type = 'application/vnd.ms-powerpoint'.
          when 'xls' or 'exe'.
            content_type = 'application/octet-stream'.
          when 'gif'.
            content_type = 'image/gif'.
          when 'jpg' or 'jpeg'.
            content_type = 'image/pjpeg'.
          when 'htm' or 'html'.
            content_type = 'text/html'.
        endcase.
        dsn = filename.
        OPEN DATASET dsn FOR INPUT IN BINARY MODE.
        IF sy-subrc NE 0.
          zmessage = 'Error opening file'.
          navigation->set_parameter( name = 'zmessage' value = zmessage ).
          navigation->goto_page( 'downloaderror.htm' ).
          exit.
        ENDIF.
        DO.
          READ DATASET dsn INTO <b>file</b>.
          EXIT.
        ENDDO.
        CLOSE DATASET dsn.
    set response data to be the file content
      runtime->server->response->set_data( <b>file</b> ).
      runtime->server->response->set_header_field(
                                    name  = 'Content-Type'
                                    value = content_type ).
      concatenate 'attachment; filename=' filename into content_disposition.
      runtime->server->response->set_header_field(
                                    name = 'Content-Disposition'
                                    value = content_disposition ).
    set the file size in the response
      content_length = xstrlen( file ).
      runtime->server->response->set_header_field(
                                name  = 'Content-Length'
                                value = content_length ).
      runtime->server->response->delete_header_field(
                                name = 'Cache-Control' ).
      runtime->server->response->delete_header_field(
                                name = 'Expires' ).
      navigation->response_complete( ).
    Thanks
    Ajay

    Hi Brian,
    I have the same problem as Ajay Yeluguri. In http mode I can generate a download of an Excel document but when we use the portal in https it doesn't work.
    When I try to download using https it does not pull the file name and path and when I choose download I have a error message : "Internet Explorer cannot download from ..."
    I've test the point 3.2 "... including file up/download" of the BSP application IT00 and it works fine in http and https mode. My problem is not the upload but the download. And in this application the uploaded document is opened in the Internet Explorer window but I want to generate a Save as... window to download the file.
    Have you an idea what i can do to solve my problem.
    Thanks
    Yann

  • Cannot open pdf files downloaded using firefox. They open fine using safari, and used to open fine before my latest update of firefox.????

    I am running the latest version of snow leopard on my mac. Since the last update of Firefox, I have not been able to open any newly downloaded pdf's. I get a message that says "The file cannot be opened.
    it may be damaged or use a file format that preview doesn't recognize."
    When I download using Safari, everything works fine. I have been using Firefox for a long time and all of my bookmarks are in Firefox.

    I also disabled adobe npapi plug-in and now the pdf files open as usual.

  • PDF files download as JSP

    I just upgraded to Leopard 10.5.6 this weekend from Tiger 10.4.11 then upgraded to 10.5.8. All went well except for a small glitch in Mail which I got fixed with the help of this forum. My newest problem is this morning I went online to my bank to download our monthly statement which always is in PDF format. The file downloaded fine, except the file title says it's a PDF, but the extension is .jsp. I contacted the bank and they have changed nothing so I am wondering is there a setting I need to change somewhere that would affect the download? At present I haven't found an application that will open .jsp files, but first I want to get them back to PDF format. Any suggestions will be appreciated.

    Title Man wrote:
    I just upgraded to Leopard 10.5.6 this weekend from Tiger 10.4.11 then upgraded to 10.5.8. All went well except for a small glitch in Mail which I got fixed with the help of this forum. My newest problem is this morning I went online to my bank to download our monthly statement which always is in PDF format. The file downloaded fine, except the file title says it's a PDF, but the extension is .jsp. I contacted the bank and they have changed nothing so I am wondering is there a setting I need to change somewhere that would affect the download? At present I haven't found an application that will open .jsp files, but first I want to get them back to PDF format.
    Have you tried renaming the file so that its extension is ".pdf"? I believe I regularly download PDF files that have "jsp" in the file name, but renaming them corrects the problem.

  • Error in File uploading using jsp

    I am tring to upload files to a mysql database using jsp.I have used BLOB type to store files.Iam using the JDBC driver mysql-connector-java-2.0-14-bin to connect the database with the jsp API.My problem is when i try to transfer a file of size which is less than the possible capacity through blob ,which is 1048576 bytes ( for example when a file of size 916KB is attempted to transfer) the following error is being generated.
    java.lang.IllegalArgumentException: Packet is larger than max_allowed_packet from server configuration of 1048576 bytes
         at com.mysql.jdbc.Buffer.ensureCapacity(Unknown Source)
         at com.mysql.jdbc.Buffer.writeBytesNoNull(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at org.apache.jsp.file3$jsp._jspService(file3$jsp.java:110)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:201)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:381)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:473)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:190)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2347)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:468)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.connector.http.HttpProcessor.process(HttpProcessor.java:1027)
         at org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor.java:1125)
         at java.lang.Thread.run(Thread.java:484)
    java.lang.IllegalArgumentException: Packet is larger than max_allowed_packet from server configuration of 1048576 bytes
         at com.mysql.jdbc.Buffer.ensureCapacity(Unknown Source)
         at com.mysql.jdbc.Buffer.writeBytesNoNull(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at org.apache.jsp.file3$jsp._jspService(file3$jsp.java:110)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:201)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:381)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:473)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:190)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2347)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:468)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.connector.http.HttpProcessor.process(HttpProcessor.java:1027)
         at org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor.java:1125)
         at java.lang.Thread.run(Thread.java:484)
    My uploading code in jsp is as follows.
         <% try{
              Class.forName("org.gjt.mm.mysql.Driver").newInstance();
              Connection dbCon = DriverManager.getConnection("jdbc:mysql:///uoc");
              out.println("Connection done !");
              Statement stmt = dbCon.createStatement();
              out.println("Statement Created !");
    ResultSet rs = stmt.executeQuery("SELECT * FROM blob_test)
    stmt.close();
    dbCon.close();
    out.println("<br><br> <b>Data Successfully selected !<b>");
    } //try
    catch(SQLException e){
         out.println(" <br> ");
         out.println("Sorry ! problem in selecting a data "+e.toString());
         out.println(" <br> ");
                   e.printStackTrace();
    %>
    Please help .I thank You in advance for any help .

    Have you tried increasing the BLOB field greater than 1048576 or using a smaller file of say 1 or 2k as a test? There is no guarantee that the database will store the file with exactly the same size as the file on the filesystem, so the file might be more than 916k in the database.
    Using BLOBs is a great way to destroy the performance of your database by the way :)

  • Anybody have a resolution for PRIAMOS file download using a Mac OSX 10.6.8 and Adobe Reader XI?

    Does anyone have experience of the EU PRIAMOS file download system? I am experiencing difficulties in downloading files in Adobe Reader format ( I have set the default PDF reader to Adobe Reader).
    The PRIAMOS system can only communicate with Windows 32bit - Mozilla Firefox 2 and higher or......
    IE 6 or 7
    IE 7 or 8 (in compatibility mode)
    Supported PDF programmes are:
    Adobe Reader 8.1 or higher
    My Adobe Reader software is the latest version (Adobe Reader XI for Mac with latest update as at 10 Sept 2013)
    The PRIAMOS system does not officially support Mac computers, but PRIAMOS has been used successfully with OS X version 10.5.8 (Leopard) and Mozilla Firefox (2.5) (with built in PDF reader disabled and Adobe Reader enabled) and Adobe Reader 8.1
    Any help would be gratefully appreciated

    Oops, I hit return before I was finished!
    In short, does anyone have any ideas apart from those I've tried. One solution seems to be to go back to 10.6.4 - one of the other discussions seem to indicate that the probelm comes in with 10.6.8.
    Thanks!

  • File download using servlet and jsp. File Dialog comes twice

    Hi
    I was trying to download a file using servlet. There is a link which calls the servlet. When I click on the link file dialog box comes up. On selecting Open it again shows me the file dialog box. I changed the method from POST to GET and it worked properly.
    My question is why does it work with GET and not with POST. I am aware of the differences between POST and GET but am not able to come to a rational explanation for this behaviour.
    Please if anyone can explain this to me I am going crazy thinking an answer for this.
    Thank you.
    Regards
    Jay

    Hi Jay,
    I also have the same question. Why does it work with GET and not for POST?. If you were able to find the answer please let me know.
    Thank you.
    Regards,
    Aravind

  • 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

  • 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 with JSP

    I have found some code within this forum that I have been attempting to use to allow customers to download text files to their PC's. The code below is what I have come up with from my understandings on exactly how it should work, but it just will not work ...
    Am I correct in assuming that the file that I want to make available for download is specified within the File f = new File(path+filename); section???
    I have made the path variable refer directly to the file system (/disk2/invoice/) as well as via http (http://domain.com/invoice/) but it will not work !!!
    It returns the save/open dialog but as soon as I select an option it returns a windows error prompt as follows:
    Internet Explorer cannot download ...p?filename=123414_76453_437 from www.domain.com.
    Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later.
    Can someone please tell me, where am I supposed to reference the file to be downloaded and how am I to reference it ???
    <%
    // get the file name from the calling page
    String filename = request.getParameter("filename");
    //get the file path to the file I want to make available via download
    String path = getServletContext().getInitParameter("invoicePath");
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition","attachment; filename=\""+filename+"\";");
    int iRead;
    FileInputStream stream = null;
    try {
         File f = new File(path+filename);
         stream = new FileInputStream(f);
         while ((iRead = stream.read()) != -1) {
              out.write(iRead);
         out.flush();
    finally {
         if (stream != null) {
              stream.close();
    %>
    <%@ page import="java.io.*,javax.servlet.*,java.util.* " contentType="text/html" %>
    <html>
    finally we have success ...     
    </html>

    For those of you who are still having issues that have been unresolved trying to download a file from a webserver to a client, I have finally figured out how to do so ...
    The following code now works for me on Solaris running Tomcat 3.1 and on W2K running JRun 3.2 ...
    Issue 1: I specified a contentType=text/html in the page specification ... This must be removed ...
    <%@ page ... contentType=text/html%>
    Issue 2: The new File() reference must be a direct path to the file on the operating system. This does not work if it is referenced with a http path.
    Other than that, I have included the code that I use to make files available for download on our webserver.
    <%@ page import="java.io.*,javax.servlet.*,java.util.* "%>
    <%
    // get the file name
    String filename = request.getParameter("filename");
    //get the file path
    String path = getServletContext().getInitParameter("invoicePath");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition","attachment; filename=\""+filename+"\";");
    int iRead;
    FileInputStream stream = null;
    try {
         File f = new File("/disk2/wwwhome/psmerged/invoice/" + filename);
         stream = new FileInputStream(f);
         while ((iRead = stream.read()) != -1) {
              out.write(iRead);
         out.flush();
    finally {
         if (stream != null) {
              stream.close();
    %>

  • 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.

  • 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

Maybe you are looking for

  • How to use P=name for Physical path name via t-cd:file

    Hello experts, I want to define physical path name using <P=name> for add-on programs. It is desirable to save files on another drive from SAP installed drive. I don't know which profile parameter can be changed. I'm afraid if standard logic wouldn't

  • Is there anyway to get iCloud without upgrading to Lion?

    I really don't want to upgrade my OS but I just got an iPhone and would like to sync without using iTunes.

  • Imovie is messing up

    I am working on a Tribute video for my 31 year old dear brother who passed away 2 years ago. I have almost 2 hours worth of clippings of home videos i am trying to embed into many pictures in another project that is already 1 and a half hours long. I

  • When to use the Export To Data Moderler design option

    Hi, Is there an advantage or difference between sending someone a model created using the Export > "To Data Modeler Design" tool as opposed to just sending them a copy of the folder tree for the same model? If yes, could you please explain what the d

  • Strange behavior from a TextInput

    Hello there. I have a strange behavior from a TextInput component and i want a little help. I have created a movieclip within. Inside is just a simple textinput component. When i'm dragging the clip from the library to the stage a test the movie ever