Storing and Retrieving doc/pdf/xls files in SQL Server 2005 using asp.net csharp

8. August 2009

Create a Table in your Database as showing.


CREATE TABLE [Files]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[FileName] [nvarchar](250) NOT NULL,
[Extension] [nvarchar](5) NOT NULL,
[flag] [bit] NOT NULL DEFAULT ((0)),
[Content] [image] NULL
)

uploading file function

using (SqlConnection cnn = new SqlConnection(“Connection String”))
{
cnn.Open();
SqlCommand cmd = new SqlCommand(“spx_FileInsertion”, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(“@FileName”, “FileName”));
cmd.Parameters.Add(new SqlParameter(“@Extension”, “Extension”));
cmd.Parameters.Add(new SqlParameter(“@Content”, “byte array(byte[]) of uploaded file”));
cnn.Close()
}



To get Download this method will use.
string strExtenstion = “extension of retrieved file”;
byte[] bytFile = “Byte array retrieved from database”;

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

if (strExtenstion == “.doc” || strExtenstion == “.docx”)
{
Response.ContentType = “application/vnd.ms-word”;
Response.AddHeader(“content-disposition”,
“attachment;filename=Tr.doc”);
}
else if (strExtenstion == “.xls” || strExtenstion == “.xlsx”)
{
Response.ContentType = “application/vnd.ms-excel”;
Response.AddHeader(“content-disposition”,
“attachment;filename=Tr.xls”);
}
else if (strExtenstion == “.pdf”)
{
Response.ContentType = “application/pdf”;
Response.AddHeader(“content-disposition”,
“attachment;filename=Tr.pdf”);
}


Response.BinaryWrite(bytFile);

Response.End();


Author: Aamir Hasan     औथोर: आमिर हसन       أثر أمير حسن .

ALL, asp.net, SQL 2005 & 2008 , , ,



User Name: Guest

Your Ip: 38.107.191.92
Time: