This discussion is archived
3 Replies Latest reply: Feb 23, 2011 2:21 AM by 824073 RSS

Downloading a file from a DB

800320 Newbie
Currently Being Moderated
Hi,

I want to download a binary file from the DB and prompt the user to save or open it i.e the "File download" dialog box that shows up when we try to download a file in many websites.

I understand that is done by the browser but may be wrong. So can you please tell me once I get the Inputstream from the DB using JDBC where should I write it so that it shows up the "File download" dialog box in a browser.

Thanks
  • 1. Re: Downloading a file from a DB
    ++sja Explorer
    Currently Being Moderated
    If you are storing a binary file in a CLOB and want to send it to a browser using a servlet, try googling for CLOB servlet. Compare the examples you find, as some of them might not be quite perfect.
  • 2. Re: Downloading a file from a DB
    sabre150 Expert
    Currently Being Moderated
    sja wrote:
    If you are storing a binary file in a CLOB and want to send it to a browser using a servlet, try googling for CLOB servlet. Compare the examples you find, as some of them might not be quite perfect.
    'binary file' and CLOB are not compatible. BLOBs are used to store binary data and CLOBs are used to store character data.
  • 3. Re: Downloading a file from a DB
    824073 Explorer
    Currently Being Moderated
    I presume you're using a servlet for the http communication?

    Just do the following:
    response.setContentType("application/x-download");
    response.setHeader("Content-Disposition", "attachment; filename=abc");
    The first line sets the content type. application/x-download is a generic content type, you can use a more specific content type if available for your data (like application/vnd.ms-excel for an excel file, see http://www.iana.org/assignments/media-types/index.html for an overview of available types).
    The second line sets the filename. Replace "abc" by the filename you want the user to see.
    Both these statements should be executed before you write any data to the outputstream.

    Then all you have to do is write the data from your InputStream to the servlets OutputStream, like this (pseudo code):
    int data = 0;
    while((data = input.read()) >= 0) {
      out.write(data);
    }
    if you're writing a large file you may want to use an array as a buffer instead of writing it out byte-per-byte.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points