Aug 19, 2013

How to Save and Retrieve File in SQL Server Table

1.)  Design

Save and Retrieve File in SQL Table :
Select File To Upload :
File ID to Download :

2.) Table
  
ID
FileName
Extension
Content
1
ShowMIS_BODRptS
.PDF
<Binary data>
2
a.xls
.xls
<Binary data>
3
test.txt
.txt
<Binary data>
4
test.sql
.sql
<Binary data>
5
ShowMIS_BODRptS
.pdf
<Binary data>




3.) Code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    string ConnString = "Data Source=MySource;Initial Catalog=db_Test; user id=MyId;pwd=MyPWD;                                       Connect Timeout=200000;";
    protected void Page_Load(object sender, EventArgs e)
    {
        /*  -- *IMP* ----
         * Before Save and Retrieve files, Create Following table and Sp's in ur DATABASE
         *
            CREATE TABLE [TestTable]
                (
                         [ID] [int] IDENTITY(1,1) NOT NULL,
                         [FileName] [nvarchar](15) NOT NULL,
                         [Extension] [nvarchar](5) NOT NULL,
                         [Content] [image] NULL
                )
            -------------------------------------

                Create  Proc InsertFile
                        @FileName nvarchar(15) ,
                        @Extension nvarchar(5) ,
                        @Content image
                AS

                Insert INTO TestTable
                ( [FileName],Extension ,Content )
                VALUES
                (@FileName  ,@Extension ,@Content)

            --------------------------------------
                ---- GetFile 1
                CREATE Proc GetFile
                        @FileID int
                AS

                Select FileName ,Extension ,Content from TestTable where                         ID=@FileID
        */

    }
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (FileUpload1.HasFile == true)
            {
                
                byte[] FileByte = new byte[FileUpload1.FileContent.Length];
                FileByte = FileUpload1.FileBytes;    
                string Ext="." + FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf('.') + 1);
                using (SqlConnection cnn = new SqlConnection(ConnString))
                {
                    cnn.Open();
                    SqlCommand cmd = new SqlCommand("InsertFile", cnn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter("@FileName", FileUpload1.FileName));
                    cmd.Parameters.Add(new SqlParameter("@Extension", Ext));
                    cmd.Parameters.Add(new SqlParameter("@Content", FileByte));
                    cmd.ExecuteNonQuery();
                    cnn.Close();
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
    protected void BtnGet_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtFileID.Text.Length > 0)
            {
                DataSet ds = new DataSet();
                using (SqlConnection cnn = new SqlConnection(ConnString))
                {
                    SqlDataAdapter da = new SqlDataAdapter("GetFile " + txtFileID.Text + "", cnn);
                    cnn.Open();
                    da.Fill(ds);
                    cnn.Close();
                }

                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {

                    string strFilename = ds.Tables[0].Rows[0]["FileName"].ToString();
                    string strExtenstion = ds.Tables[0].Rows[0]["Extension"].ToString();
                    Byte[] bytFile = (Byte[])ds.Tables[0].Rows[0]["Content"];
                    strFilename = strFilename + "" + strExtenstion;

                    Response.Clear();
                    Response.Buffer = true;

                    if (strExtenstion.ToLower() == ".doc" || strExtenstion == ".docx")
                    {
                        Response.ContentType = "application/vnd.ms-word";
                        Response.AddHeader("content-disposition", "attachment;filename=" + strFilename);
                    }
                    else if (strExtenstion.ToLower() == ".xls" || strExtenstion == ".xlsx")
                    {
                        Response.ContentType = "application/vnd.ms-excel";
                        Response.AddHeader("content-disposition", "attachment;filename=" + strFilename);
                    }
                    else if (strExtenstion.ToLower() == ".pdf")
                    {
                        Response.ContentType = "application/pdf";
                        Response.AddHeader("content-disposition", "attachment;filename=" + strFilename);
                    }
                    else
                    {
                        Response.ContentType = "application/" + ds.Tables[0].Rows[0]["Extension"].ToString();
                        Response.AddHeader("content-disposition", "attachment;filename=" + strFilename);

                    }

                    Response.Charset = "";
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);

                    // If you write,
                    // Response.Write(bytFile1);
                    // then you will get only 13 byte in bytFile.
                    Response.ContentType = "application/octet-stream";
                    Response.BinaryWrite(bytFile);
                    Response.Flush();
                    Response.End();
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
}


No comments:

Post a Comment

What is the use of n-tier architecture and 3-tier architecture?

how to implement 3-tier architecture in asp.net using c#. 3-Tier architecture is also called layered architecture. Some people called it ...