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,
Step 1: Let's create a table first
- CREATE TABLE [dbo].[tblFiles](
- [id] [int ] IDENTITY(1,ane) NOT Zip ,
- [Name ] [ varchar ](fifty) NOT NULL ,
- [ContentType] [nvarchar](200)NOT Aught ,
- [Data] [varbinary](max ) NOT Nada
- )ON [ PRIMARY ] TEXTIMAGE_ON [ Primary ]
Pace 2: Open Visual Studio
Open up Visual Studio File->New Website, as shown below:
Select ASP.Cyberspace empty Website and give the suitable proper noun every bit DocumentSaveInBinary, as shown beneath:
Now let's create FileUpload Command, every bit shown below:
- < asp:FileUpload ID = "FileUpload1" runat = "server" />
- < 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:
- < asp:GridView ID = "GridView1" runat = "server"
- AutoGenerateColumns = "false" CssClass = "tabular array" >
- < Columns >
- < asp:BoundField DataField = "Proper name" HeaderText = "File Name" />
- < asp:TemplateField ItemStyle-HorizontalAlign = "Heart" >
- < ItemTemplate >
- < asp:LinkButton ID = "lnkDownload" runat = "server" Text = "Download" OnClick = "DownloadFile"
- CommandArgument = '<%# Eval("Id") %>' > </ asp:LinkButton >
- </ ItemTemplate >
- </ asp:TemplateField >
- </ Columns >
- </ 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:
- < %@ Page Language = "C#" AutoEventWireup = "true" CodeFile = "DocumentUpload.aspx.cs" Inherits = "_Default" % >
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML one.0 Transitional//EN" "http://world wide web.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- < html xmlns = "http://www.w3.org/1999/xhtml" >
- < head id = "Head1" runat = "server" >
- < title > </ championship >
- < link rel = "Stylesheet" href = "Styles/bootstrap.min.css" style = "" />
- < link rel = "Stylesheet" href = "Styles/bootstrap.css" />
- </ caput >
- < trunk >
- < grade id = "form1" runat = "server" >
- < div form = "container" >
- < asp:FileUpload ID = "FileUpload1" runat = "server" />
- < asp:Button ID = "btnUpload" runat = "server" Text = "Upload" OnClick = "Upload" CssClass = "btn-primary" />
- < hr />
- < asp:GridView ID = "GridView1" runat = "server"
- AutoGenerateColumns = "false" CssClass = "tabular array" >
- < Columns >
- < asp:BoundField DataField = "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 design looks as shown below:
Step 3: Now let's see the CS Code Part
Commencement include the connection string in web.config file, as shown below:
- < connectionStrings >
- < add proper noun = "constr" providerName = "System.Data.SQlClient" connectionString = "Data Source=AB-NPC1-D1A315;Initial Itemize=Examination;User ID=sa;Countersign=p@ssw0rd" />
- </ connectionStrings >
Now, we will see the showtime Action button upload, followed by the code to upload the files and finally save in the database.
Our file upload code is shown below:
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:
- 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))
- {
- cord query = "insert into tblFiles values (@Name, @ContentType, @Data)" ;
- using (SqlCommand cmd = new SqlCommand(query))
- {
- cmd.Connection = con;
- cmd.Parameters.AddWithValue("@Name" , filename);
- cmd.Parameters.AddWithValue("@ContentType" , contentType);
- cmd.Parameters.AddWithValue("@Data" , bytes);
- con.Open();
- cmd.ExecuteNonQuery();
- con.Close();
- }
- }
- }
- }
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:
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:
Hence, my final CS lawmaking is shown below:
- using System;
- using Arrangement.Web;
- using System.Spider web.Security;
- using Organization.Spider web.UI;
- using System.Web.UI.WebControls;
- using Organisation.Web.UI.WebControls.WebParts;
- using Organization.Web.UI.HtmlControls;
- using Organization.IO;
- using System.Data;
- using Organization.Data.SqlClient;
- using System.Configuration;
- public fractional course _Default : System.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, Name from tblFiles" ;
- cmd.Connection = con;
- con.Open up();
- 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);
- string constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
- using (SqlConnection con = new SqlConnection(constr))
- {
- string query = "insert into tblFiles values (@Proper noun, @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 up();
- cmd.ExecuteNonQuery();
- con.Shut();
- }
- }
- }
- }
- Response.Redirect(Request.Url.AbsoluteUri);
- }
- protected void DownloadFile( object sender, EventArgs due east)
- {
- int id = int .Parse((sender as LinkButton).CommandArgument);
- byte [] bytes;
- string fileName, contentType;
- string constr = ConfigurationManager.ConnectionStrings[ "constr" ].ConnectionString;
- using (SqlConnection con = new SqlConnection(constr))
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- cmd.CommandText ="select Proper 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[ "Data" ];
- contentType = sdr["ContentType" ].ToString();
- fileName = sdr["Name" ].ToString();
- }
- con.Close();
- }
- }
- Response.Clear();
- Response.Buffer =true ;
- Response.Charset ="" ;
- Response.Cache.SetCacheability(HttpCacheability.NoCache);
- Response.ContentType = contentType;
- Response.AppendHeader("Content-Disposition" , "zipper; filename=" + fileName);
- Response.BinaryWrite(bytes);
- Response.Flush();
- Response.Cease();
- }
- }
- Just run the Awarding and debug on the action events to run into the FileUpload and its content, as shown beneath:
Y'all volition encounter the file name which we had downloaded.
Now let'south see the upload, as shown below:
Nosotros got the file proper noun, as shown below:
Content Type is shown beneath:
Let's see the length of that certificate which is depicted below:
Now we will encounter what we take successfully uploaded.
ConclusionThis article was about uploading the files in the database and saving them in a binary format. I hope this article was helpful.
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"