Skip to content Skip to sidebar Skip to footer

javascript get binary data from uploaded file

OverviewToday, we will see how to upload the files --  that may exist Word files, PDFs, Zip files etc. -- save them in the SQL database, retrieve these files, and download these files. This code is useful when you need to upload the various documents in an organization, perhaps to procedure the document, news etc., and other users will need to download these files to see the content. To encounter the content that you have uploaded, you have to relieve it  in Binary format. Let's beginning,

image

Step 1: Let's create a table first table

  1. CREATE TABLE  [dbo].[tblFiles](
  2.     [id] [int ] IDENTITY(1,ane) NOT Zip ,
  3.     [Name ] [ varchar ](fifty) NOT NULL ,
  4.     [ContentType] [nvarchar](200)NOT Aught ,
  5.     [Data] [varbinary](max ) NOT Nada
  6. )ON  [ PRIMARY ] TEXTIMAGE_ON [ Primary ]

Pace 2: Open Visual Studio

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

New Website

Select ASP.Cyberspace empty Website and give the suitable proper noun every bit DocumentSaveInBinary, as shown beneath:

ASP.NET Empty Website

Now let's create FileUpload Command, every bit shown below:

code

  1. < asp:FileUpload ID = "FileUpload1" runat = "server" />
  2. < asp:Push ID = "btnUpload" runat = "server" Text = "Upload" OnClick = "Upload" CssClass = "btn-primary" />

Now, let's create Gridview with download link button then that we can download the respective documents or the files, shown below:

code

  1. < asp:GridView ID = "GridView1" runat = "server"
  2. AutoGenerateColumns = "false" CssClass = "tabular array" >
  3. < Columns >
  4. < asp:BoundField DataField = "Proper name" HeaderText = "File Name" />
  5. < asp:TemplateField ItemStyle-HorizontalAlign = "Heart" >
  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 will 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 last Certificate.aspx lawmaking is equally follows:

  1. < %@ Page Language = "C#" AutoEventWireup = "true" CodeFile = "DocumentUpload.aspx.cs" Inherits = "_Default"  % >
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML one.0 Transitional//EN" "http://world wide web.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. < html xmlns = "http://www.w3.org/1999/xhtml" >
  4. < head id = "Head1" runat = "server" >
  5. < title > </ championship >
  6. < link rel = "Stylesheet" href = "Styles/bootstrap.min.css" style = "" />
  7. < link rel = "Stylesheet" href = "Styles/bootstrap.css" />
  8. </ caput >
  9. < trunk >
  10. < grade id = "form1" runat = "server" >
  11. < div form = "container" >
  12. < asp:FileUpload ID = "FileUpload1" runat = "server" />
  13. < asp:Button ID = "btnUpload" runat = "server" Text = "Upload" OnClick = "Upload" CssClass = "btn-primary" />
  14. < hr />
  15. < asp:GridView ID = "GridView1" runat = "server"
  16. AutoGenerateColumns = "false" CssClass = "tabular array" >
  17. < Columns >
  18. < asp:BoundField DataField = "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 design looks as shown below:

Design

Step 3: Now let's see the CS Code Part

Commencement include the connection string in web.config file, as shown below:

  1. < connectionStrings >
  2. < add proper noun = "constr" providerName = "System.Data.SQlClient" connectionString = "Data Source=AB-NPC1-D1A315;Initial Itemize=Examination;User ID=sa;Countersign=p@ssw0rd" />
  3. </ connectionStrings >

Now, we will see the showtime Action 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

As you lot meet in the code, mentioned to a higher place, sympathize what nosotros are saving in the table FileName, Contentype. Here, the content types are Words, PDF, image and and then on. Thus, nosotros are saving the posted file in the binary format by using Stream every bit a posted file,  which you had uploaded in Fileupload control and convertedthat file in BinaryReader, as 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. cord  query = "insert into tblFiles values (@Name, @ContentType, @Data)" ;
  11. using  (SqlCommand cmd = new  SqlCommand(query))
  12.             {
  13.                 cmd.Connection = con;
  14.                 cmd.Parameters.AddWithValue("@Name" , 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 certificate in the database by using cmd.Parameters.AddWithValue("@FieldName",FileName),

  • Similarly, we will write the code for the download, equally we had created on the click in the Gridview, every bit shown beneath:

    Code
    Hither, what we are doing in DownloadFile is, you are actually reading the bytes which you had saved in the database.

Now we will bind the Gridview, as shown beneath:

Code

Hence, my final CS lawmaking is shown below:

  1. using  System;
  2. using  Arrangement.Web;
  3. using  System.Spider web.Security;
  4. using  Organization.Spider web.UI;
  5. using  System.Web.UI.WebControls;
  6. using  Organisation.Web.UI.WebControls.WebParts;
  7. using  Organization.Web.UI.HtmlControls;
  8. using  Organization.IO;
  9. using  System.Data;
  10. using  Organization.Data.SqlClient;
  11. using  System.Configuration;
  12. public  fractional course  _Default : System.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, Name from tblFiles" ;
  29.                 cmd.Connection = con;
  30.                 con.Open up();
  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. string  constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
  47. using  (SqlConnection con = new  SqlConnection(constr))
  48.                 {
  49. string  query = "insert into tblFiles values (@Proper noun, @ContentType, @Data)" ;
  50. using  (SqlCommand cmd = new  SqlCommand(query))
  51.                     {
  52.                         cmd.Connection = con;
  53.                         cmd.Parameters.AddWithValue("@Proper noun" , filename);
  54.                         cmd.Parameters.AddWithValue("@ContentType" , contentType);
  55.                         cmd.Parameters.AddWithValue("@Data" , bytes);
  56.                         con.Open up();
  57.                         cmd.ExecuteNonQuery();
  58.                         con.Shut();
  59.                     }
  60.                 }
  61.             }
  62.         }
  63.         Response.Redirect(Request.Url.AbsoluteUri);
  64.     }
  65. protected void  DownloadFile( object  sender, EventArgs due east)
  66.     {
  67. int  id = int .Parse((sender as  LinkButton).CommandArgument);
  68. byte [] bytes;
  69. string  fileName, contentType;
  70. string  constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
  71. using  (SqlConnection con = new  SqlConnection(constr))
  72.         {
  73. using  (SqlCommand cmd = new  SqlCommand())
  74.             {
  75.                 cmd.CommandText ="select Proper 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[ "Data" ];
  83.                     contentType = sdr["ContentType" ].ToString();
  84.                     fileName = sdr["Name" ].ToString();
  85.                 }
  86.                 con.Close();
  87.             }
  88.         }
  89.         Response.Clear();
  90.         Response.Buffer =true ;
  91.         Response.Charset ="" ;
  92.         Response.Cache.SetCacheability(HttpCacheability.NoCache);
  93.         Response.ContentType = contentType;
  94.         Response.AppendHeader("Content-Disposition" , "zipper; filename="  + fileName);
  95.         Response.BinaryWrite(bytes);
  96.         Response.Flush();
  97.         Response.Cease();
  98.     }
  99. }
  • Just run the Awarding and debug on the action events to run into the FileUpload and its content, as shown beneath:

    Application

    code

Y'all volition encounter the file name which we had downloaded.

Now let'south see the upload, as shown below:

Upload

Nosotros got the file proper noun, as shown below:

code

Content Type is shown beneath:

code

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

code

Now we will encounter what we take successfully uploaded.

result
ConclusionThis article was about uploading the files in the database and saving them in a binary format. I hope this article was helpful.

millerlamonegre.blogspot.com

Source: https://www.c-sharpcorner.com/article/upload-files-and-save-into-database-in-binary-format-using-asp-net/

Post a Comment for "javascript get binary data from uploaded file"