How to do download files from jsp


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 13 of 13

Thread: How to do download files from jsp

  1. #1
    Join Date
    Jul 2005
    Posts
    3

    How to do download files from jsp

    Hi, i want to be able to have the user click on a link and download a file that is on my server. I am using j2ee and struts. I don't want the user to ever know the url of the file because I don't want that user to give the url to someone else so that they can directly download the file. Users must log into my site and depending on their userid, they have a custom list of files that they can download. Can people give me (a relative begginner) tips/code how to do this? Thanks!

  2. #2
    Join Date
    Oct 2004
    Posts
    311
    The way you want to download your file is by streaming it via a server side component if I understand correctly.
    This is usually not done via JSP pages but via Servlets.
    If you look around on the internet for articles regarding servlets, all should become clear.

  3. #3
    Join Date
    Jan 2005
    Location
    Reisterstowwn, MD
    Posts
    72
    Ok, I have been working on this too, I posted a thread not to long ago asking how to do file I/O using JSPs. As I have read/learned more I found that you should really use servlets to handle such a process, like ractoc said. A JSP is really more for dynamic presentation, while Servlets are for the more background type stuff. Anyways, I have anoter question. I created a very simple servlet that takes some information from a client by way of a form. This form then POSTs the data to my servlet, and the servlet creates an xml file in memory. This xml file is then sent through the response OutputStream. The xml text shows up in the browser and then the user can choose to save it to their local file system. How can I make it so that the servlet response causes the browser to create a download dialog (you know a Save File dialog) rather then just writing the bytes directly to the browser window.

    Would this be some type of information I have to set in the header? Or do certain MIME types cause the save as dialog to appear (I tried both apllication/xml and text/xml, and it's my guess the MIME type makes no difference on whether or not the file is downloaded or just displayed). Mabe I should just get off my lazy butt and read the HTTP RFC. I'd rather not tho .

    Thanks,
    Ryan

    P.S. aroneous54, sorry for jacking your thread bro. It sounds like you need a page that gets some type of information, then you need a servlet to process that request and either have the servlet directly create the page or maybe use some type of URL encoding, java bean, or context attributes that your JSP page could use to create the custom links. So something like this:

    JSP or HTML page that gathers info ----> Servlet that processes the request ---> Response from servlet

    or

    JSP or HTML page that gathers info ----> Servlet that processes the request and creates some type of bean or context attributes to be used by the next page ----> browser redirected to JSP page that uses the bean or context objects to create the dynamic links


    This is how I would imagine doing it, but then again I'm also still pretty much a newbie in this area, so take it with a grain of salt.
    Last edited by customwoodtek; 07-25-2005 at 01:34 AM.
    Java has 99 problems but a pointer ain't one

  4. #4
    Join Date
    Jul 2005
    Posts
    3

    I have some code but now have an error. Help!!

    Here's the situation now:

    I have a servlet that has some download code which I got off the web.

    In the servlet, the intent is to download a file. I am using IBM websphere.
    I get a "java.lang.IllegalStateException: OutputStream already obtained" error everytime I try to run this at the response.getOutputStream() line.

    I can't figure out how to get around this.

  5. #5
    Join Date
    Jan 2005
    Location
    Reisterstowwn, MD
    Posts
    72
    First off, just so everyone knows i figured out the answer to my question, you have to set the content-disposition header.

    Anyways, as for your exception, if you look at the J2EE API docs for ServletResponse (which is a parent interface for HttpServletResponse) you will see that both the getWriter method and getOutputStream method will throw an IllegalStateException if both of them are called. So if you call getWriter and then getOutputStream (or vice-versa) then the IllegalStateException willl be thrown. Basically, go back over your servlet and make sure you did not call both of these methods.

    I think the reasoning for this is because PrintWriter is actually a wrapper over the OutputStream and you cannot open the same stream twice?? Either way, you just can't do it according to the docs.

    Goodluck,
    Ryan
    Java has 99 problems but a pointer ain't one

  6. #6
    Join Date
    Oct 2004
    Posts
    311
    getting the browser to create a pop-up is done by setting the response.setContentType() to the right value. Usually this is text/html, for xml this should be text/xml, for gif image/gif and so on.
    There is one problem with xml however, since your browser understands xml, it will try and display iot first. I'm not sutre there's anything that can be done about this.

  7. #7
    Join Date
    Jan 2005
    Location
    Reisterstowwn, MD
    Posts
    72
    Quote Originally Posted by ractoc
    getting the browser to create a pop-up is done by setting the response.setContentType() to the right value. Usually this is text/html, for xml this should be text/xml, for gif image/gif and so on.
    There is one problem with xml however, since your browser understands xml, it will try and display iot first. I'm not sutre there's anything that can be done about this.
    As i said in my previous post I indeed figured it out, setting the content-type did not help. Rather, I had to set the content-disposition header to "attachment" and then specify a file name. This caused the browser to open a Save As dialog with the file name I had given.
    Java has 99 problems but a pointer ain't one

  8. #8
    Join Date
    Feb 2005
    Posts
    3

    set headers

    Servlet should have the following headers set

    This will open File Download dialog
    resp.setContentType( "application/x-download" );
    resp.setHeader( "Content-Disposition", "attachment; filename=" + downloadFileName );

    When it is inline it opens the file,
    //resp.setHeader( "Content-Disposition", "inline; filename=" + downloadFileName );

    In the following case, we get a File Download dialog, but it behaves differently
    //resp.setHeader( "Content-Type", "attachment; filename=" + downloadFileName );


    Thanks
    Nah

  9. #9
    Join Date
    Feb 2005
    Posts
    3

    File Download dialog

    I have Download servlet which downloads the results of search function in text file.
    There is no problem when I test download function in my local (WSAD)workspace. There are no errors or anything..The results are downloaded to a text file.
    When this is deployed on a WebSphere 5.1.1.3 AIX environment, for some reason the File Download dialog never pops up?

    Are there any security related settings are which are preventing File Download dialog to open when this deployed to WebSphere 5.1.1.3.

    Servlet has the following headers set
    resp.setContentType( "application/x-download" );
    resp.setHeader( "Content-Disposition", "attachment; filename=" + downloadFileName );


    In my Jsp the download button is inside a iframe.
    <input type="button" onclick="handleDownLoad(document.reportResult,'<%=viewBean.getDownloadURL() %>')"
    value="Download" title="Download <%= viewBean.getCurrentReportName()%> Report">

    Any ideas/suggestions??

    Thanks a lot
    Nah

  10. #10
    Join Date
    Oct 2004
    Posts
    311
    Have you tried setting the content type to text/plain?
    since this is the actual content type belonging to a text file.

  11. #11
    Join Date
    Feb 2005
    Posts
    3

    File Download dialog

    I have tried setting the header to text/plain.

    resp.setContentType( "text/plain" );

    But still it does not work?

    When the results are writted to text file,where this text file gets stored temporarily??

    If I dont have proper permissions on server (WebSphere 5.1.1.3 AIX environment) may be it wont open File Download dialog????

    Any ideas???

    Thanks in advance
    Nah

  12. #12
    Join Date
    Aug 2005
    Posts
    1
    I am using the following code. But it doesn't open a download dialog box. Can anyone help.

    <%
    String directory = "/APPS/../.../" ;
    String actualFileName = directory + fileName; //fileName can be a txt, zip, pdf or jpeg file name.
    String linkName = "Link" + i;

    InputStream inputStream = null;
    try {
    response.setContentType("application/Octet-Stream");
    response.setHeader("Content- Disposition","attachment;filename=" + fileName );

    int sizeRead = 256;
    byte[] buf = new byte[1024];

    File file = new File(actualFileName).getAbsoluteFile();
    URL url = file.toURL();
    inputStream = (BufferedInputStream)url.openConnection().getContent();

    while( (sizeRead = inputStream.read(buf)) != -1 )
    {
    out.write(sizeRead);
    }

    } catch(Exception ex) {
    System.out.println("Exception " + ex.getMessage());
    }
    inputStream.close();
    %>

    <Table>
    <TR>
    <TD>
    <a name="<%=linkName%>" href="<%= actualFileName %>" ><%=fileName%></a>
    </TD>
    </TR>
    </Table>

  13. #13
    Join Date
    May 2010
    Posts
    1
    I am also facign similiar problem when i run on my local machine I am able to download the file but when the application is deployed they use HTTPS instead of HTTP as compare to local...i am getting error

    Internet Explorer cannot download file from ...

    why on HTTPS this piece of code doesnt works


    String filename = "attachment; filename=StackTrace_" + userName.trim() + "_" +
    DateUtil.getYear( DateUtil.getCurrentDate() ) + "_" +
    DateUtil.getMonth( DateUtil.getCurrentDate() ) + "_" +
    DateUtil.getDay( DateUtil.getCurrentDate() ) + ".html";

    HttpServletResponse response = ((ABCActionHttpContext)ctx).getResponse();
    response.setContentType( "application/x-downloadx-download" + "; charset=UTF-8" );
    response.setHeader( "Content-Disposition", filename );

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center