Uploading and Downloading Multiple Files in SQL Using ASP.Net

Introduction

Today we'll learn to upload multiple files to the SQL Server Database using the ASP.NET Web Forms Application. At first we'll define the table in the database and insert the file information into it. You can insert any type of file like image, PDF, documents and so on.

So, let's get started to create this scenario using the following procedure:

  • Create ASP.NET Web Forms Application
  • Adding SQL Server Database
  • Adding Entity Data Model
  • Adding and Working with Content WebForm
  • Application Execution

Create ASP.NET Web Forms Application

In this section, we'll create the Web Forms application using the following procedure.

Step 1: Open the Visual Studio 2013 and click on the "New Project".

Step 2: Under the Web tab, select the ASP.NET Web Application and enter the name as in the following:

Creating Web Application in VS 2013

Step 3: Select the WebForms Project Template from the "One ASP.NET" wizard.

WebForms Project Template in VS 2013

Visual Studio automatically creates the ASP.NET Web Forms Application. Now proceed to the next section.

Adding SQL Server Database

In this section we'll create the database by adding the SQL Server Database file. Follow the instructions below.

Step 1: In the Solution Explorer, right-click on the App_Data folder and click Add new item.

Step 2: Select SQL Server Database and enter the database name as in the following:

Creating Sql Server Database File

Step 3: Now in Server Explorer, expand the SampleFile.mdf and right-click on the tables to add a new table.

Creating Table using ServerExplorer

Step 4: Write the following query and click on Update to execute the query.

  1. CREATE TABLE [dbo].[UploadFile]  
  2. (  
  3.     [Id] INT NOT NULL PRIMARY KEY IDENTITY(1,1),  
  4.     [NameVARCHAR(150) NOT NULL,  
  5.     [SizeINT NOT NULL,  
  6.     [ContentType] VARCHAR(200) NOT NULL,  
  7.     [Extension] VARCHAR(10) NOT NULL,  
  8.     [Content] VARBINARY(MAXNOT NULL  
  9. )

Adding Entity Data Model

The database has been created and now we'll add the model using the following procedure.

Step 1: In the Solution Explorer, right-click on the Models to add the ADO.NET Entity Data Model.

Choosing Model in Entity Data Model

Step 2: Select the mdf file in the data connection.

Choosing Data Connection in Entity Data Model

Step 3: Now select the table from the database and click on Finish.

Choosing Table in Entity Data Model

Now the model is ready. Follow the next section.

Adding and Working with Content Web Form

Now in this section we'll add the web form and make some code. Use the following procedure to do that.

Step 1: In the Solution Explorer, right-click on the application to add a new item.

Step 2: Select the Web Forms with Master Page and enter the form name.

Creating Web Form with Master Page

Selecting Master Page 

Step 3: Now replace the code with the code below:

  1. <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">  
  2.     <script src="Scripts/jquery-1.10.2.js"></script>  
  3.     <script type="text/javascript">  
  4.         $(function () {  
  5.             debugger;  
  6.             var DivElement = $('#MultipleFileUploader');  
  7.             var i = $('#MultipleFileUploader p').size() + 1;  
  8.             $('#AddAnotherUploader').on('click'function () {  
  9.                 $('<p><input type="file" ID="FileUploader1' + i + '" name="FileUploader1' + i + '" class="form-control" />  
  10.                  </p>').appendTo(DivElement);  
  11.                 i++;  
  12.                 return false;  
  13.             });  
  14.         });  
  15.     </script>  
  16.     <div class="form-horizontal">  
  17.         <h4>Uploading Multiple Files</h4>  
  18.         <hr />  
  19.         <asp:ValidationSummary runat="server" CssClass="text-danger" />  
  20.         <div class="form-group">  
  21.             <asp:Label runat="server" CssClass="col-md-2 control-label">Choose File</asp:Label>  
  22.             <div class="col-md-10" id="MultipleFileUploader">  
  23.                 <p>  
  24.                     <asp:FileUpload runat="server" ID="FileUploader" CssClass="form-control" />  
  25.                     <a href="#" id="AddAnotherUploader">Add Files</a>  
  26.                 </p>  
  27.             </div>  
  28.         </div>  
  29.         <div class="form-group">  
  30.             <div class="col-md-offset-2 col-md-10">  
  31.                 <asp:Button runat="server" ID="BtnUploadFile" OnClick="BtnUploadFile_Click"   
  32.                 Text="Upload Files" CssClass="btn btn-default" />  
  33.             </div>  
  34.         </div>  
  35.         <div class="form-group">  
  36.             <asp:Label runat="server" CssClass="col-md-2 control-label">Select Files:</asp:Label>  
  37.             <div class="col-md-10">  
  38.                 <asp:GridView runat="server" ID="DataGridView" AutoGenerateColumns="false"  
  39.                  OnRowCommand="DataGridView_RowCommand" CssClass="form-control">  
  40.                     <Columns>  
  41.                         <asp:BoundField HeaderText="File Name" DataField="Name" />  
  42.                         <asp:BoundField HeaderText="File Size" DataField="Size" />  
  43.                         <asp:TemplateField HeaderText="Get File">  
  44.                             <ItemTemplate>  
  45.                                 <asp:LinkButton ID="LbnDownload" runat="server" CommandName="DownloadFile"   
  46.                                     CommandArgument='<%# Eval("Id") %>'>Download</asp:LinkButton>  
  47.                             </ItemTemplate>  
  48.                         </asp:TemplateField>  
  49.                     </Columns>  
  50.                 </asp:GridView>  
  51.             </div>  
  52.         </div>  
  53.     </div>  
  54. </asp:Content>

Step 4: Now in the code of the web form, replace the code with the code below:

  1. using MultipleFileUploadApp.Models;  
  2. using System;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.UI.WebControls;  
  7. namespace MultipleFileUploadApp  
  8. {  
  9.     public partial class Sample : System.Web.UI.Page  
  10.     {  
  11.         protected void Page_Load(object sender, EventArgs e)  
  12.         {  
  13.             this.Form.Enctype = "multipart/form-data";  
  14.             if (!IsPostBack)  
  15.             {  
  16.                 GetUploadedFiles();  
  17.             }  
  18.         }  
  19.         private void GetUploadedFiles()  
  20.         {  
  21.             using (SampleFileEntities SampleDb = new SampleFileEntities())  
  22.             {  
  23.                 DataGridView.DataSource = SampleDb.UploadFiles.ToList();  
  24.                 DataGridView.DataBind();  
  25.             }  
  26.         }  
  27.         protected void DataGridView_RowCommand(object sender, GridViewCommandEventArgs e)  
  28.         {  
  29.             if (e.CommandName == "DownloadFile")  
  30.             {  
  31.                 int File_ID = Convert.ToInt32(e.CommandArgument.ToString());  
  32.                 using (SampleFileEntities SampleDb = new SampleFileEntities())  
  33.                 {  
  34.                     var File = SampleDb.UploadFiles.Where(f=>f.Id.Equals(File_ID)).FirstOrDefault();  
  35.                     if (File != null)  
  36.                     {  
  37.                         Response.ContentType = File.ContentType;  
  38.                         Response.AddHeader("content-disposition""attachment; filename=" + File.Name);  
  39.                         Response.BinaryWrite(File.Content);  
  40.                         Response.Flush();  
  41.                         Response.End();  
  42.                     }  
  43.                 }  
  44.             }  
  45.         }  
  46.         protected void BtnUploadFile_Click(object sender, EventArgs e)  
  47.         {  
  48.             HttpFileCollection File_Collection = Request.Files;  
  49.             using (SampleFileEntities SampleDb = new SampleFileEntities())  
  50.             {  
  51.                 foreach (string File_Uploader in File_Collection)  
  52.                 {  
  53.                     HttpPostedFile Posted_File= File_Collection[File_Uploader];  
  54.                     if (Posted_File.ContentLength > 0)  
  55.                     {  
  56.                         BinaryReader Binary_Reader = new BinaryReader(Posted_File.InputStream);  
  57.                         byte[] File_Buffer = Binary_Reader.ReadBytes(Posted_File.ContentLength);  
  58.                         SampleDb.UploadFiles.Add(new UploadFile  
  59.                         {  
  60.                             Name=Posted_File.FileName,  
  61.                             ContentType=Posted_File.ContentType,  
  62.                             Extension=Path.GetExtension(Posted_File.FileName),  
  63.                             Size=Posted_File.ContentLength,  
  64.                             Content=File_Buffer  
  65.                         });  
  66.                     }  
  67.                 }  
  68.                 SampleDb.SaveChanges();  
  69.             }  
  70.             GetUploadedFiles();  
  71.         }  
  72.     }  
  73. } 

Application Execution

Step 1: Open the Site.Master page and add the following highlighted code:

  1. <li><a runat="server" href="~/">Home</a></li>  
  2. <li><a runat="server" href="~/About">About</a></li>  
  3. <li><a runat="server" href="~/Contact">Contact</a></li>  
  4. <li><a runat="server" href="~/Sample">Sample</a></li>

Step 2: Press F5 or Ctrl+F5 to run the application and open the form.

WebForms Application Home Page

Step 3: Select the files and you can also add other files. Now click on the Upload Files button.

Uploading Multiple Files from Web Application

Step 4: You can also download files from the database as in the following:

Database Information in Web Appliaciton

Summary

This article described how to upload multiple files with their parameter, like name and size and store them in the database and you can also learn to download the uploaded files from the database. Thanks for reading.


Similar Articles