banner



How To Save Uploaded File In Database In Vb.net

Introduction

This article gives an caption about how to upload and save a file in the database as VARBINARY Data in asp.net using c# and vb.internet. Here I'll as well explain how to upload files in asp.cyberspace besides as how to save the file in the SQL Server database equally VARBINARY data.

While nosotros working with any spider web, windows, or mobile application sometimes we need to upload/salve some documents or files such as Word, Excel, CSV, PDF, images, audio and video, and many other files into a database. Basically, many developers salve original files or documents in a specific folder and save file path into the database and while they want to access any file or document, they fetch file path for a specific file from the database and based on that file path they become the file from the binder. Suppose, unfortunately, a file is deleted or renamed in the folder then they are not able to access those files or documents. Then, today in this commodity I'll testify yous how to relieve files directly into the database in VARBINARY data. This will allow you to access any file from the database.

Hither, I'll explain how to catechumen whatever files such as Word, Excel, CSV, PDF, images, audio and video, and many other files into VARBINARY data and salve them into the SQL server database with a uncomplicated, easy, and understandable example using C# and VB.NET with Bootstrap iv.

Requirement

  • File upload in ASP.Net using C# and VB.Cyberspace with Bootstrap 4.
  • Save uploaded files or documents into the SQL server database in VARBINARY format.
  • Display uploaded files in a filigree view.

Implementation

Let's outset with an example of the employee management system. Hither nosotros will save employee-related  documents such as contour moving-picture show, identity of the employee such as election card too as other documents of employees such equally agreements, address proof and etc into the database.

To save VARBINARY data of the uploaded documents of the employee into the SQL server database, first, we demand to create a table into the database, so starting time we will create a table with the proper noun tblEmpIdentity. To create a tabular array in the SQL server database you need to execute the post-obit SQL script equally given below.

Create Table

  1. CREATE TABLE  [dbo].[tblEmpIdentity] (
  2.     [FileID]INT              IDENTITY (1, 1) NOT Zip ,
  3.     [EmployeeID]INT Zip ,
  4.     [EmployeeName]VARCHAR  (50) Zero ,
  5.     [DocumentName]VARCHAR  (l) NULL ,
  6.     [FileName]VARCHAR  (50) NULL ,
  7.     [FileContentType] NVARCHAR (200)NULL ,
  8.     [FileData ]       VARBINARY (MAX ) Goose egg ,
  9. CONSTRAINT  [PK_tblEmpIdentity] Chief KEY  CLUSTERED ([FileID] ASC )
  10. );

As you can see in the above script, hither nosotros created a column for FileID, EmployeeID, EmployeeName, DocumentName, FileName, ContentType, FileData where FileID is the primary key of the table.

Now, we will write the following HTML lawmaking into aspx file, where we will blueprint our form with a dropdown box for employee selection, file upload control, upload button likewise as i grid view to display information of uploaded files of the employee.

HTML

  1. <html xmlns= "http://world wide web.w3.org/1999/xhtml" >
  2. <head id="Head1"  runat= "server" >
  3.     <title>File Upload Example</championship>
  4.     <link rel="stylesheet"  href= "https://maxcdn.bootstrapcdn.com/bootstrap/four.3.1/css/bootstrap.min.css"  />
  5.     <script blazon="text/javascript"  src= "https://ajax.googleapis.com/ajax/libs/jquery/iii.4.1/jquery.min.js" ></script>
  6.     <script type="text/javascript"  src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.vii/umd/popper.min.js" ></script>
  7.     <script type="text/javascript"  src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.ane/js/bootstrap.min.js" ></script>
  8. </head>
  9. <trunk>
  10.     <form id="form1"  runat= "server" >
  11.         <divclass = " container" >
  12.             <br />
  13.             <h1>File Upload Example</h1>
  14.             <br />
  15.             <divgrade = "form-row" >
  16.                 <divclass = "col" >
  17.                     <asp:DropDownList id="ddlEmployees"  runat= "server"  CssClass= "form-control dropdown" >
  18.                         <asp:ListItem value="0" >-- Select Employee --</asp:ListItem>
  19.                         <asp:ListItem value="1" >Nikunj Satasiya</asp:ListItem>
  20.                         <asp:ListItem value="2" >Hiren Dobariya</asp:ListItem>
  21.                         <asp:ListItem value="3" >Vivek Ghadiya</asp:ListItem>
  22.                         <asp:ListItem value="3" >Shreya Patel</asp:ListItem>
  23.                     </asp:DropDownList>
  24.                 </div>
  25.                 <divclass = "col" >
  26.                     <asp:TextBox ID="txtDocument"  runat= "server"  CssClass= "form-control"  placeholder= "DocumentName" ></asp:TextBox>
  27.                 </div>
  28.             </div>
  29.             <br />
  30.             <divclass = " row" >
  31.                 <asp:FileUpload ID="FileUploadEmployees"  runat= "server"  CssClass= "btn"  />
  32.             </div>
  33.             <br />
  34.             <asp:Button ID="btnUploadFile"  runat= "server"  Text= "Upload"  CssClass= "btn btn-primary"  OnClick= "btnUploadFile_click"  />
  35.             <hr />
  36.             <asp:GridView ID="grdEmployees"  runat= "server"  Width= "100%"  CssClass= "table table-bordered"  AutoGenerateColumns= "false" >
  37.                 <Columns>
  38.                     <asp:BoundField DataField="FileID "  Visible= "false"  HeaderText= "FileID "  />
  39.                     <asp:BoundField DataField="EmployeeName"  HeaderText= "EmployeeName"  />
  40.                     <asp:BoundField DataField="DocumentName"  HeaderText= "DocumentName"  />
  41.                     <asp:BoundField DataField="FileName"  HeaderText= "FileName"  />
  42.                     <asp:BoundField DataField="FileData"  HeaderText= "FileData"  />
  43.                 </Columns>
  44.             </asp:GridView>
  45.         </div>
  46.     </course>
  47. </body>
  48. </html>

As you lot can see in the HTML code written above, where we have linked CSS and Javascript for Bootstrap four and with assistance of bootstrap course we designed a grade using the dropdown box for employee choice. File upload control is for browsing a file from the organization, and upload button is for converting and uploading files into the database in VARBINARY format as well as a grid view for displaying uploaded records.

Before we offset the bodily code we demand to create a database connection with our spider web application and for that, we need to write the following connection string into the spider web.config file.

Web.Config

  1. <connectionStrings>
  2.     <add name="ConnectionStrings"  connectionString= "Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\Nikunj\codingvila\bin\Debug\DBcodingvila.mdf;Integrated Security=Truthful;Connect Timeout=thirty" />
  3.   </connectionStrings >

Later on the creation of a database connectedness we need to import the post-obit namespaces into lawmaking-behind.

Namespaces

C#

  1. using  Arrangement.IO;
  2. using  System.Data;
  3. using  System.Data.SqlClient;
  4. using  Organisation.Configuration;

VB.Internet

  1. Imports  Organization.IO
  2. Imports  System.Information
  3. Imports  Organisation.Data.SqlClient
  4. Imports  System.Configuration

Now, we need to write a C# lawmaking for browsing and reading file content in BINARY data and storing information technology into the SQL server database. and for that, we need to write the following code in the on click event of the upload button.

C#

  1. protected void  btnUploadFile_click( object  sender, EventArgs due east)
  2.     {
  3. string  empFilename = Path.GetFileName(FileUploadEmployees.PostedFile.FileName);
  4. string  FilecontentType = FileUploadEmployees.PostedFile.ContentType;
  5. using  (Stream s = FileUploadEmployees.PostedFile.InputStream)
  6.         {
  7. using  (BinaryReader br = new  BinaryReader(s))
  8.             {
  9. byte [] Databytes = br.ReadBytes((Int32)due south.Length);
  10. string  ConnectionStrings = ConfigurationManager.ConnectionStrings[ "ConnectionStrings" ].ConnectionString;
  11. using  (SqlConnection con = new  SqlConnection(ConnectionStrings))
  12.                 {
  13. string  query = "INSERT INTO tblEmpIdentity VALUES (@EmployeeID, @EmployeeName, @DocumentName, @FileName, @FileContentType, @FileData)" ;
  14. using  (SqlCommand cmd = new  SqlCommand(query))
  15.                     {
  16.                         cmd.Connection = con;
  17.                         cmd.Parameters.AddWithValue("@EmployeeID" , ddlEmployees.SelectedItem.Value);
  18.                         cmd.Parameters.AddWithValue("@EmployeeName" , ddlEmployees.SelectedItem.Text);
  19.                         cmd.Parameters.AddWithValue("@DocumentName" , txtDocument.Text);
  20.                         cmd.Parameters.AddWithValue("@FileName" , empFilename);
  21.                         cmd.Parameters.AddWithValue("@FileContentType" , FilecontentType);
  22.                         cmd.Parameters.AddWithValue("@FileData" , Databytes);
  23.                         con.Open();
  24.                         cmd.ExecuteNonQuery();
  25.                         con.Shut();
  26.                     }
  27.                 }
  28.             }
  29.         }
  30.         Response.Redirect(Request.Url.AbsoluteUri);
  31.     }

VB.Cyberspace

  1. Protected Sub  btnUploadFile_click(sender Every bit Object , e Every bit  EventArgs)
  2. Dim  empFilename As String  = Path.GetFileName(FileUploadEmployees.PostedFile.FileName)
  3. Dim  FilecontentType Equally String  = FileUploadEmployees.PostedFile.ContentType
  4.         Using sAs  Stream = FileUploadEmployees.PostedFile.InputStream
  5.             Using brEqually New  BinaryReader(s)
  6. Dim  Databytes As Byte () = br.ReadBytes( CType (south.Length, Int32))
  7. Dim  ConnectionStrings As Cord  = ConfigurationManager.ConnectionStrings( "ConnectionStrings" ).ConnectionString
  8.                 Using conAs New  SqlConnection(ConnectionStrings)
  9. Dim  query As String  = "INSERT INTO tblEmpIdentity VALUES  (@EmployeeID, @EmployeeName, @DocumentName, @FileName, @FileContentType, @FileData)"
  10.                     Using cmdAs New  SqlCommand(query)
  11.                         cmd.Connection = con
  12.                         cmd.Parameters.AddWithValue("@EmployeeID" , ddlEmployees.SelectedItem.Value)
  13.                         cmd.Parameters.AddWithValue("@EmployeeName" , ddlEmployees.SelectedItem.Text)
  14.                         cmd.Parameters.AddWithValue("@DocumentName" , txtDocument.Text)
  15.                         cmd.Parameters.AddWithValue("@FileName" , empFilename)
  16.                         cmd.Parameters.AddWithValue("@FileContentType" , FilecontentType)
  17.                         cmd.Parameters.AddWithValue("@FileData" , Databytes)
  18.                         con.Open()
  19.                         cmd.ExecuteNonQuery()
  20.                         con.Close()
  21. End  Using
  22. End  Using
  23. Finish  Using
  24. Stop  Using
  25.         Response.Redirect(Request.Url.AbsoluteUri)
  26. Stop Sub

Caption

As y'all can see in the written code above, first we fetched a proper noun of the uploaded file and stored it in a local variable empFilename, so nosotros fetched and stored the content type of the uploaded file and stored it in variable FileContentType. Then we read the contents of the file and stored in-stream variables and then created an object of binary reader class that reads primitive information types as binary values in specific encoding and uses that file content and stored binary data in a byte array. And so nosotros accept created a database connexion and command object as well as prepared a parameterized SQL query for inserting records into the tblEmpIdentity table and passing required parameters with values and executes SQL statement and inserts a record into the SQL server database.

Finally, as per the requirement described above, we need to display uploaded files or documents of the employees into the grid view, so we will fetch all the records from the tblEmpIdentity table and bind those records with the grid view.

C#

  1. private void  GetEmployees()
  2.     {
  3. string  ConnectionStrings = ConfigurationManager.ConnectionStrings[ "ConnectionStrings" ].ConnectionString;
  4. using  (SqlConnection Connectedness = new  SqlConnection(ConnectionStrings))
  5.         {
  6. using  (SqlCommand cmd = new  SqlCommand())
  7.             {
  8.                 cmd.CommandText ="SELECT FileID, EmployeeName, DocumentName, FileName, Catechumen(VARCHAR(fifty), FileData, 1) AS FileData  from tblEmpIdentity WITH (NOLOCK)" ;
  9.                 cmd.Connection = Connection;
  10.                 Connection.Open();
  11.                 grdEmployees.DataSource = cmd.ExecuteReader();
  12.                 grdEmployees.DataBind();
  13.                 Connexion.Close();
  14.             }
  15.         }
  16.     }

VB.NET

  1. Private Sub  GetEmployees()
  2. Dim  ConnectionStrings As Cord  = ConfigurationManager.ConnectionStrings( "ConnectionStrings" ).ConnectionString
  3.         Using conAs New  SqlConnection(ConnectionStrings)
  4.             Using cmdEqually New  SqlCommand()
  5.                 cmd.CommandText ="SELECT FileID, EmployeeName, DocumentName, FileName, CONVERT(VARCHAR(50), FileData, one) AS FileData  from tblEmpIdentity WITH (NOLOCK)"
  6.                 cmd.Connectedness = con
  7.                 con.Open up()
  8.                 grdEmployees.DataSource = cmd.ExecuteReader()
  9.                 grdEmployees.DataBind()
  10.                 con.Close()
  11. End  Using
  12. Cease  Using
  13. End Sub

Explanation

Every bit yous can come across in the written code above, nosotros take created a function GetEmployees for displaying records from the tblEmpIdentity tabular array. Nosotros take fetched connection string from web.config file and created an object of SQL connection class for database connection and so created an object for SQL command grade, prepared a SQL statement for fetching records from the database and finally executed the created SQL argument and assigned  a effect set to filigree view as a data source.

Now, we have to call the created method above on the load outcome of the page to view the inserted records into the database.

C#

  1. protected void  Page_Load( object  sender, EventArgs e)
  2.     {
  3. if  (!IsPostBack)
  4.         {
  5.             GetEmployees();
  6.         }
  7.     }

VB.Internet

  1. Protected Sub  Page_Load(sender Every bit Object , e As  EventArgs) Handles Me .Load
  2. If Not  IsPostBack And so
  3.             GetEmployees()
  4. Terminate If
  5. End Sub

Output

Summary

In this commodity, we learned how to upload files in ASP.Cyberspace using C# and VB.NET and nosotros learned how to save the file into the SQL server database in VARBINARY data.

Source: https://www.c-sharpcorner.com/article/upload-and-save-file-in-database-as-varbinary-data-in-asp-net-using-c-sharpintroducti/

Posted by: seegerlivendede.blogspot.com

0 Response to "How To Save Uploaded File In Database In Vb.net"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel