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,

image

Step 1: Let's create a tabular array first table

  1. CREATE TABLE  [dbo].[tblFiles](
  2.     [id] [int ] IDENTITY(1,1) Non NULL ,
  3.     [Proper name ] [ varchar ](50) NOT Null ,
  4.     [ContentType] [nvarchar](200)Not NULL ,
  5.     [Information] [varbinary](max ) Not NULL
  6. )ON  [ Chief ] TEXTIMAGE_ON [ Master ]

Footstep 2: Open Visual Studio

Open up Visual Studio File->New Website, equally shown below:

New Website

Select ASP.Net empty Website and give the suitable name as DocumentSaveInBinary, as shown below:

ASP.NET Empty Website

Now let'southward create FileUpload Command, as shown below:

code

  1. < asp:FileUpload ID = "FileUpload1" runat = "server" />
  2. < 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:

code

  1. < asp:GridView ID = "GridView1" runat = "server"
  2. AutoGenerateColumns = "false" CssClass = "table" >
  3. < Columns >
  4. < asp:BoundField DataField = "Proper noun" HeaderText = "File Name" />
  5. < asp:TemplateField ItemStyle-HorizontalAlign = "Center" >
  6. < ItemTemplate >
  7. < asp:LinkButton ID = "lnkDownload" runat = "server" Text = "Download" OnClick = "DownloadFile"
  8. CommandArgument = '<%# Eval("Id") %>' > </ asp:LinkButton >
  9. </ ItemTemplate >
  10. </ asp:TemplateField >
  11. </ Columns >
  12. </ 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:

  1. < %@ Page Language = "C#" AutoEventWireup = "true" CodeFile = "DocumentUpload.aspx.cs" Inherits = "_Default"  % >
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. < html xmlns = "http://world wide web.w3.org/1999/xhtml" >
  4. < head id = "Head1" runat = "server" >
  5. < title > </ title >
  6. < link rel = "Stylesheet" href = "Styles/bootstrap.min.css" mode = "" />
  7. < link rel = "Stylesheet" href = "Styles/bootstrap.css" />
  8. </ caput >
  9. < body >
  10. < grade id = "form1" runat = "server" >
  11. < div grade = "container" >
  12. < asp:FileUpload ID = "FileUpload1" runat = "server" />
  13. < asp:Push ID = "btnUpload" runat = "server" Text = "Upload" OnClick = "Upload" CssClass = "btn-primary" />
  14. < hr />
  15. < asp:GridView ID = "GridView1" runat = "server"
  16. AutoGenerateColumns = "false" CssClass = "table" >
  17. < Columns >
  18. < asp:BoundField DataField = "Proper name" HeaderText = "File Name" />
  19. < asp:TemplateField ItemStyle-HorizontalAlign = "Center" >
  20. < ItemTemplate >
  21. < asp:LinkButton ID = "lnkDownload" runat = "server" Text = "Download" OnClick = "DownloadFile"
  22. CommandArgument = '<%# Eval("Id") %>' > </ asp:LinkButton >
  23. </ ItemTemplate >
  24. </ asp:TemplateField >
  25. </ Columns >
  26. </ asp:GridView >
  27. </ div >
  28. </ form >
  29. </ body >
  30. </ html >

Our final pattern looks as shown below:

Design

Stride iii: Now let's see the CS Code Office

First include the connection cord in web.config file, equally shown below:

  1. < connectionStrings >
  2. < add together proper name = "constr" providerName = "System.Data.SQlClient" connectionString = "Data Source=AB-NPC1-D1A315;Initial Catalog=TEST;User ID=sa;Password=p@ssw0rd" />
  3. </ 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.

Database

Our file upload code is shown below:

Code

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:

  1. using  (Stream fs = FileUpload1.PostedFile.InputStream)
  2. {
  3. using  (BinaryReader br = new  BinaryReader(fs))
  4.     {
  5. byte [] bytes = br.ReadBytes((Int32)fs.Length);
  6. byte [] bytes = br.ReadBytes((Int32)fs.Length);
  7. string  constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
  8. using  (SqlConnection con = new  SqlConnection(constr))
  9.         {
  10. string  query = "insert into tblFiles values (@Name, @ContentType, @Data)" ;
  11. using  (SqlCommand cmd = new  SqlCommand(query))
  12.             {
  13.                 cmd.Connection = con;
  14.                 cmd.Parameters.AddWithValue("@Proper noun" , filename);
  15.                 cmd.Parameters.AddWithValue("@ContentType" , contentType);
  16.                 cmd.Parameters.AddWithValue("@Data" , bytes);
  17.                 con.Open();
  18.                 cmd.ExecuteNonQuery();
  19.                 con.Close();
  20.             }
  21.         }
  22.     }
  23. }

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:

    Code
    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:

Code

Hence, my concluding CS code is shown beneath:

  1. using  Organization;
  2. using  System.Spider web;
  3. using  Organization.Web.Security;
  4. using  System.Web.UI;
  5. using  System.Web.UI.WebControls;
  6. using  Arrangement.Web.UI.WebControls.WebParts;
  7. using  System.Web.UI.HtmlControls;
  8. using  System.IO;
  9. using  Organisation.Data;
  10. using  System.Information.SqlClient;
  11. using  System.Configuration;
  12. public  partial class  _Default : Organisation.Web.UI.Page
  13. {
  14. protected void  Page_Load( object  sender, EventArgs e)
  15.     {
  16. if  (!IsPostBack)
  17.         {
  18.             BindGrid();
  19.         }
  20.     }
  21. private void  BindGrid()
  22.     {
  23. string  constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
  24. using  (SqlConnection con = new  SqlConnection(constr))
  25.         {
  26. using  (SqlCommand cmd = new  SqlCommand())
  27.             {
  28.                 cmd.CommandText ="select Id, Proper noun from tblFiles" ;
  29.                 cmd.Connection = con;
  30.                 con.Open();
  31.                 GridView1.DataSource = cmd.ExecuteReader();
  32.                 GridView1.DataBind();
  33.                 con.Close();
  34.             }
  35.         }
  36.     }
  37. protected void  Upload( object  sender, EventArgs e)
  38.     {
  39. string  filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
  40. string  contentType = FileUpload1.PostedFile.ContentType;
  41. using  (Stream fs = FileUpload1.PostedFile.InputStream)
  42.         {
  43. using  (BinaryReader br = new  BinaryReader(fs))
  44.             {
  45. byte [] bytes = br.ReadBytes((Int32)fs.Length);
  46. cord  constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
  47. using  (SqlConnection con = new  SqlConnection(constr))
  48.                 {
  49. string  query = "insert into tblFiles values (@Name, @ContentType, @Data)" ;
  50. using  (SqlCommand cmd = new  SqlCommand(query))
  51.                     {
  52.                         cmd.Connexion = con;
  53.                         cmd.Parameters.AddWithValue("@Name" , filename);
  54.                         cmd.Parameters.AddWithValue("@ContentType" , contentType);
  55.                         cmd.Parameters.AddWithValue("@Data" , bytes);
  56.                         con.Open();
  57.                         cmd.ExecuteNonQuery();
  58.                         con.Close();
  59.                     }
  60.                 }
  61.             }
  62.         }
  63.         Response.Redirect(Request.Url.AbsoluteUri);
  64.     }
  65. protected void  DownloadFile( object  sender, EventArgs e)
  66.     {
  67. int  id = int .Parse((sender as  LinkButton).CommandArgument);
  68. byte [] bytes;
  69. string  fileName, contentType;
  70. cord  constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
  71. using  (SqlConnection con = new  SqlConnection(constr))
  72.         {
  73. using  (SqlCommand cmd = new  SqlCommand())
  74.             {
  75.                 cmd.CommandText ="select Name, Data, ContentType from tblFiles where Id=@Id" ;
  76.                 cmd.Parameters.AddWithValue("@Id" , id);
  77.                 cmd.Connection = con;
  78.                 con.Open();
  79. using  (SqlDataReader sdr = cmd.ExecuteReader())
  80.                 {
  81.                     sdr.Read();
  82.                     bytes = (byte [])sdr[ "Information" ];
  83.                     contentType = sdr["ContentType" ].ToString();
  84.                     fileName = sdr["Proper noun" ].ToString();
  85.                 }
  86.                 con.Close();
  87.             }
  88.         }
  89.         Response.Clear();
  90.         Response.Buffer =truthful ;
  91.         Response.Charset ="" ;
  92.         Response.Cache.SetCacheability(HttpCacheability.NoCache);
  93.         Response.ContentType = contentType;
  94.         Response.AppendHeader("Content-Disposition" , "attachment; filename="  + fileName);
  95.         Response.BinaryWrite(bytes);
  96.         Response.Flush();
  97.         Response.End();
  98.     }
  99. }
  • Simply run the Awarding and debug on the action events to see the FileUpload and its content, as shown below:

    Application

    code

You lot will see the file name which we had downloaded.

Now let's see the upload, equally shown beneath:

Upload

We got the file name, as shown below:

code

Content Blazon is shown below:

code

Let's see the length of that document which is depicted below:

code

At present we will come across what we take successfully uploaded.

result
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#"

ارسال یک نظر

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel