Showing posts with label Saving Word Document to the Sql Server. Show all posts
Showing posts with label Saving Word Document to the Sql Server. Show all posts

Wednesday, August 26, 2009

Saving Word Document to the Sql Server

First we have to create a table to store the Word Document
CREATE TABLE [dbo].[File1](
[id] [int] IDENTITY(1,1) NOT NULL,
[Filename] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[FileBytes] [varbinary](max) NOT NULL
) ON [PRIMARY]
The Design view of a Web Form
<asp:Label id="lblFile" Text="wordDocument" AssociatedControlID="upFile" runat="server" />
<asp:FileUpload id="upFile" runat="Server" />
<asp:Button id="btnAdd" Text="Add Documents" runat="server" OnClick="btnAdd_Click" />
<hr />
<asp:Repeater id="rptFiles" DataSourceID="srcFiles" runat="Server">
<HeaderTemplate>
<ul class="fileList">
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink id="lnkFile" Text='<%#Eval("FileName")%>' NavigateUrl='<%#Eval("id","~/FileHandler.ashx?id={0}")%>' runat="Server" />
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
<asp:SqlDataSource id="srcFiles"
ConnectionString="<%$ ConnectionStrings:FileDBConnectionString %>"
SelectCommand="SELECT [id], [Filename] FROM [File1]"
InsertCommand="INSERT INTO [File1] (Filename, FileBytes) values (@fileName,@FileBytes)"
runat="server">
<InsertParameters>
<asp:ControlParameter Name="FileName" ControlID="upFile" PropertyName="FileName" />
<asp:ControlParameter Name="FileBytes" ControlID="upFile" PropertyName="FileBytes" />
</InsertParameters>
</asp:SqlDataSource>
The Code Behind of Button Add Documents
if (upFile.HasFile)
{
if (CheckFileType(upFile.FileName))
srcFiles.Insert();
}
The Function CheckFileType
bool CheckFileType(string fileName)
{
return Path.GetExtension(fileName).ToLower() == ".doc";
}
Then Add Custom Handler on to the Page
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/msword";
SqlConnection con = new SqlConnection(@"Data Source=SHEEBAN\SQLEXPRESS;Initial Catalog=FileDB;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select filebytes from [file1] where id=@id", con);
cmd.Parameters.AddWithValue("@id", context.Request["id"]);
using (con)
{
con.Open();
byte[] file = (byte[])cmd.ExecuteScalar();
context.Response.BinaryWrite(file);
}
}
public bool IsReusable
{
get
{
return false;
}
}