Tuesday, June 19, 2012

Retrieve files from Oracle 10g using Asp.net


In this post “Retrieve files from Oracle 10g using Asp.net”, we will see how to retrieve Document, Excel and PDF files saved in Oracle database, in Byte format using Asp.Net.  

Refer the post Save files to Oracle 10g using Asp.net, to see on how to save the documents to the database using Asp.Net

Add a button to the .aspx page as follows

<asp:Button ID="cmdDownload"
runat="server"
Text="Download"
onclick="cmdDownload_Click" / >

Once the button is added move to the code-behind file to write the download logic as follows.

protected void cmdDownload_Click(object sender, EventArgs e)
{
    DownloadDocument();
}
//
private void DownloadDocument()
{
    // Retrieve Details from the DB
    string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    objConn = new OracleConnection(strConn);
    objCmd = new OracleCommand("SELECT DOCUMENT_NAME, DOCUMENT_TYPE, DOCUMENT From BUSINESS_REQUIREMENTS_DOCUMENT Where DOCUMENT_ID = 3", objConn);
    //
    objConn.Open();
    OracleDataReader dr = objCmd.ExecuteReader();
    dr.Read();
    strFileName = dr.GetString(0);
    strFileExtension = dr.GetString(1);
    Byte[] byteDoc = new Byte[(dr.GetBytes(2, 0, null, 0, int.MaxValue))];
    dr.GetBytes(2, 0, byteDoc, 0, byteDoc.Length);
    dr.Close();
    objConn.Close();
    //
    Response.Clear();
    Response.Buffer = true;
    if (strFileExtension.ToUpper() == ".DOC" || strFileExtension.ToUpper() == ".DOCX")
    {
       Response.ContentType = "application/vnd.ms-word";
       Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + "." + strFileExtension);
    }
    else if (strFileExtension.ToUpper() == ".XLS" || strFileExtension.ToUpper() == ".XLSX")
    {
       Response.ContentType = "application/vnd.ms-excel";
       Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + "." + strFileExtension);
    }
    else if (strFileExtension.ToUpper() == ".PDF")
    {
       Response.ContentType = "application/pdf";
       Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + "." + strFileExtension);
    }
    //
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.BinaryWrite(byteDoc);
    Response.End();
}

Run the application click on the Download button, the file will be retrieved from the Database, converted to the actual format and allows the user to save the file.


Search Flipkart Products:
Flipkart.com

1 comment:

Cherry said...

First of all, thank you for your post. Your post have help me tremendously. However, I have a question. How about those file with .txt? How shall we retrieve these file from Oracle database?