Upload Files to Sql Database Using C#
OverviewToday, we will come across how to upload the files -- that may be Word files, PDFs, Zip files etc. -- save them in the SQL database, retrieve these files, and download these files. This code is useful when y'all demand to upload the various documents in an system, perhaps to process the document, news etc., and other users volition need to download these files to see the content. To see the content that you take uploaded, you have to salve it in Binary format. Let's kickoff,
Step 1: Let's create a tabular array first
- CREATE TABLE [dbo].[tblFiles](
- [id] [int ] IDENTITY(1,1) Non NULL ,
- [Proper name ] [ varchar ](50) NOT Null ,
- [ContentType] [nvarchar](200)Not NULL ,
- [Information] [varbinary](max ) Not NULL
- )ON [ Chief ] TEXTIMAGE_ON [ Master ]
Footstep 2: Open Visual Studio
Open up Visual Studio File->New Website, equally shown below:
Select ASP.Net empty Website and give the suitable name as DocumentSaveInBinary, as shown below:
Now let'southward create FileUpload Command, as shown below:
- < asp:FileUpload ID = "FileUpload1" runat = "server" />
- < asp:Button ID = "btnUpload" runat = "server" Text = "Upload" OnClick = "Upload" CssClass = "btn-primary" />
Now, permit's create Gridview with download link button so that we can download the respective documents or the files, shown below:
- < asp:GridView ID = "GridView1" runat = "server"
- AutoGenerateColumns = "false" CssClass = "table" >
- < Columns >
- < asp:BoundField DataField = "Proper noun" HeaderText = "File Name" />
- < asp:TemplateField ItemStyle-HorizontalAlign = "Center" >
- < ItemTemplate >
- < asp:LinkButton ID = "lnkDownload" runat = "server" Text = "Download" OnClick = "DownloadFile"
- CommandArgument = '<%# Eval("Id") %>' > </ asp:LinkButton >
- </ ItemTemplate >
- </ asp:TemplateField >
- </ Columns >
- </ asp:GridView >
Here, you volition run across that inside Gridview <asp:BoundField/> is used, that shows HeaderText as FileName in the Gridview. In that <Itemtemplate></Itemtemplate> inside Itemtemplate, you need to bind Link button with ID="lnkDownload" OnClick="DownloadFile".
Thus, my final Document.aspx code is as follows:
- < %@ Page Language = "C#" AutoEventWireup = "true" CodeFile = "DocumentUpload.aspx.cs" Inherits = "_Default" % >
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- < html xmlns = "http://world wide web.w3.org/1999/xhtml" >
- < head id = "Head1" runat = "server" >
- < title > </ title >
- < link rel = "Stylesheet" href = "Styles/bootstrap.min.css" mode = "" />
- < link rel = "Stylesheet" href = "Styles/bootstrap.css" />
- </ caput >
- < body >
- < grade id = "form1" runat = "server" >
- < div grade = "container" >
- < asp:FileUpload ID = "FileUpload1" runat = "server" />
- < asp:Push ID = "btnUpload" runat = "server" Text = "Upload" OnClick = "Upload" CssClass = "btn-primary" />
- < hr />
- < asp:GridView ID = "GridView1" runat = "server"
- AutoGenerateColumns = "false" CssClass = "table" >
- < Columns >
- < asp:BoundField DataField = "Proper name" HeaderText = "File Name" />
- < asp:TemplateField ItemStyle-HorizontalAlign = "Center" >
- < ItemTemplate >
- < asp:LinkButton ID = "lnkDownload" runat = "server" Text = "Download" OnClick = "DownloadFile"
- CommandArgument = '<%# Eval("Id") %>' > </ asp:LinkButton >
- </ ItemTemplate >
- </ asp:TemplateField >
- </ Columns >
- </ asp:GridView >
- </ div >
- </ form >
- </ body >
- </ html >
Our final pattern looks as shown below:
Stride iii: Now let's see the CS Code Office
First include the connection cord in web.config file, equally shown below:
- < connectionStrings >
- < add together proper name = "constr" providerName = "System.Data.SQlClient" connectionString = "Data Source=AB-NPC1-D1A315;Initial Catalog=TEST;User ID=sa;Password=p@ssw0rd" />
- </ connectionStrings >
Now, we volition see the first Action push button upload, followed by the code to upload the files and finally save in the database.
Our file upload code is shown below:
Every bit y'all meet in the code, mentioned in a higher place, understand what we are saving in the table FileName, Contentype. Here, the content types are Words, PDF, image and and so on. Thus, nosotros are saving the posted file in the binary format by using Stream every bit a posted file, which y'all had uploaded in Fileupload control and convertedthat file in BinaryReader, equally shown below:
- using (Stream fs = FileUpload1.PostedFile.InputStream)
- {
- using (BinaryReader br = new BinaryReader(fs))
- {
- byte [] bytes = br.ReadBytes((Int32)fs.Length);
- byte [] bytes = br.ReadBytes((Int32)fs.Length);
- string constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
- using (SqlConnection con = new SqlConnection(constr))
- {
- string query = "insert into tblFiles values (@Name, @ContentType, @Data)" ;
- using (SqlCommand cmd = new SqlCommand(query))
- {
- cmd.Connection = con;
- cmd.Parameters.AddWithValue("@Proper noun" , filename);
- cmd.Parameters.AddWithValue("@ContentType" , contentType);
- cmd.Parameters.AddWithValue("@Data" , bytes);
- con.Open();
- cmd.ExecuteNonQuery();
- con.Close();
- }
- }
- }
- }
This is used to insert the document in the database by using cmd.Parameters.AddWithValue("@FieldName",FileName),
- Similarly, we will write the lawmaking for the download, as we had created on the click in the Gridview, as shown below:
Here, what we are doing in DownloadFile is, you are actually reading the bytes which yous had saved in the database.
Now nosotros will demark the Gridview, as shown beneath:
Hence, my concluding CS code is shown beneath:
- using Organization;
- using System.Spider web;
- using Organization.Web.Security;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using Arrangement.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- using System.IO;
- using Organisation.Data;
- using System.Information.SqlClient;
- using System.Configuration;
- public partial class _Default : Organisation.Web.UI.Page
- {
- protected void Page_Load( object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindGrid();
- }
- }
- private void BindGrid()
- {
- string constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
- using (SqlConnection con = new SqlConnection(constr))
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- cmd.CommandText ="select Id, Proper noun from tblFiles" ;
- cmd.Connection = con;
- con.Open();
- GridView1.DataSource = cmd.ExecuteReader();
- GridView1.DataBind();
- con.Close();
- }
- }
- }
- protected void Upload( object sender, EventArgs e)
- {
- string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
- string contentType = FileUpload1.PostedFile.ContentType;
- using (Stream fs = FileUpload1.PostedFile.InputStream)
- {
- using (BinaryReader br = new BinaryReader(fs))
- {
- byte [] bytes = br.ReadBytes((Int32)fs.Length);
- cord constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
- using (SqlConnection con = new SqlConnection(constr))
- {
- string query = "insert into tblFiles values (@Name, @ContentType, @Data)" ;
- using (SqlCommand cmd = new SqlCommand(query))
- {
- cmd.Connexion = con;
- cmd.Parameters.AddWithValue("@Name" , filename);
- cmd.Parameters.AddWithValue("@ContentType" , contentType);
- cmd.Parameters.AddWithValue("@Data" , bytes);
- con.Open();
- cmd.ExecuteNonQuery();
- con.Close();
- }
- }
- }
- }
- Response.Redirect(Request.Url.AbsoluteUri);
- }
- protected void DownloadFile( object sender, EventArgs e)
- {
- int id = int .Parse((sender as LinkButton).CommandArgument);
- byte [] bytes;
- string fileName, contentType;
- cord constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
- using (SqlConnection con = new SqlConnection(constr))
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- cmd.CommandText ="select Name, Data, ContentType from tblFiles where Id=@Id" ;
- cmd.Parameters.AddWithValue("@Id" , id);
- cmd.Connection = con;
- con.Open();
- using (SqlDataReader sdr = cmd.ExecuteReader())
- {
- sdr.Read();
- bytes = (byte [])sdr[ "Information" ];
- contentType = sdr["ContentType" ].ToString();
- fileName = sdr["Proper noun" ].ToString();
- }
- con.Close();
- }
- }
- Response.Clear();
- Response.Buffer =truthful ;
- Response.Charset ="" ;
- Response.Cache.SetCacheability(HttpCacheability.NoCache);
- Response.ContentType = contentType;
- Response.AppendHeader("Content-Disposition" , "attachment; filename=" + fileName);
- Response.BinaryWrite(bytes);
- Response.Flush();
- Response.End();
- }
- }
- Simply run the Awarding and debug on the action events to see the FileUpload and its content, as shown below:
You lot will see the file name which we had downloaded.
Now let's see the upload, equally shown beneath:
We got the file name, as shown below:
Content Blazon is shown below:
Let's see the length of that document which is depicted below:
At present we will come across what we take successfully uploaded.
ConclusionThis commodity was about uploading the files in the database and saving them in a binary format. I hope this article was helpful.
parkeronewarthill46.blogspot.com
Source: https://www.c-sharpcorner.com/article/upload-files-and-save-into-database-in-binary-format-using-asp-net/
0 Response to "Upload Files to Sql Database Using C#"
ارسال یک نظر