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.

CREATE TABLE [dbo].[UploadFile]

(

    [Id] INT NOT NULL PRIMARY KEY IDENTITY(1,1),

    [Name] VARCHAR(150) NOT NULL,

    [Size] INT NOT NULL,

    [ContentType] VARCHAR(200) NOT NULL,

    [Extension] VARCHAR(10) NOT NULL,

    [Content] VARBINARY(MAX) NOT NULL

)

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:

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <script src="Scripts/jquery-1.10.2.js"></script>

    <script type="text/javascript">

        $(function () {

            debugger;

            var DivElement = $('#MultipleFileUploader');

            var i = $('#MultipleFileUploader p').size() + 1;

 

            $('#AddAnotherUploader').on('click'function () {

                $('<p><input type="file" ID="FileUploader1' + i + '" name="FileUploader1' + i + '" class="form-control" />

                 </p>').appendTo(DivElement);

                i++;

                return false;

            });           

        });

    </script>

    <div class="form-horizontal">

        <h4>Uploading Multiple Files</h4>

        <hr />

        <asp:ValidationSummary runat="server" CssClass="text-danger" />

        <div class="form-group">

            <asp:Label runat="server" CssClass="col-md-2 control-label">Choose File</asp:Label>

            <div class="col-md-10" id="MultipleFileUploader">

                <p>

                    <asp:FileUpload runat="server" ID="FileUploader" CssClass="form-control" />

                    <a href="#" id="AddAnotherUploader">Add Files</a>

                </p>

            </div>

        </div>

        <div class="form-group">

            <div class="col-md-offset-2 col-md-10">

                <asp:Button runat="server" ID="BtnUploadFile" OnClick="BtnUploadFile_Click" 

                Text="Upload Files" CssClass="btn btn-default" />

            </div>

        </div>

        <div class="form-group">

            <asp:Label runat="server" CssClass="col-md-2 control-label">Select Files:</asp:Label>

            <div class="col-md-10">

                <asp:GridView runat="server" ID="DataGridView" AutoGenerateColumns="false"

                 OnRowCommand="DataGridView_RowCommand" CssClass="form-control">

                    <Columns>

                        <asp:BoundField HeaderText="File Name" DataField="Name" />

                        <asp:BoundField HeaderText="File Size" DataField="Size" />

                        <asp:TemplateField HeaderText="Get File">

                            <ItemTemplate>

                                <asp:LinkButton ID="LbnDownload" runat="server" CommandName="DownloadFile" 

                                    CommandArgument='<%# Eval("Id"%>'>Download</asp:LinkButton>

                            </ItemTemplate>

                        </asp:TemplateField>

                    </Columns>

                </asp:GridView>

            </div>

        </div>

    </div>

</asp:Content>

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

using MultipleFileUploadApp.Models;

using System;

using System.IO;

using System.Linq;

using System.Web;

using System.Web.UI.WebControls;

 

namespace MultipleFileUploadApp

{

    public partial class Sample : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            this.Form.Enctype = "multipart/form-data";

            if (!IsPostBack)

            {

                GetUploadedFiles();

            }

        }

 

        private void GetUploadedFiles()

        {

            using (SampleFileEntities SampleDb = new SampleFileEntities())

            {

                DataGridView.DataSource = SampleDb.UploadFiles.ToList();

                DataGridView.DataBind();

            }

        }

 

        protected void DataGridView_RowCommand(object sender, GridViewCommandEventArgs e)

        {

            if (e.CommandName == "DownloadFile")

            {

                int File_ID = Convert.ToInt32(e.CommandArgument.ToString());

                using (SampleFileEntities SampleDb = new SampleFileEntities())

                {

                    var File = SampleDb.UploadFiles.Where(f=>f.Id.Equals(File_ID)).FirstOrDefault();

                    if (File != null)

                    {

                        Response.ContentType = File.ContentType;

                        Response.AddHeader("content-disposition""attachment; filename=" + File.Name);

                        Response.BinaryWrite(File.Content);

                        Response.Flush();

                        Response.End();

                    }

                }

            }

        }

 

        protected void BtnUploadFile_Click(object sender, EventArgs e)

        {

            HttpFileCollection File_Collection = Request.Files;

            using (SampleFileEntities SampleDb = new SampleFileEntities())

            {

                foreach (string File_Uploader in File_Collection)

                {

                    HttpPostedFile Posted_File= File_Collection[File_Uploader];

                    if (Posted_File.ContentLength > 0)

                    {

                        BinaryReader Binary_Reader = new BinaryReader(Posted_File.InputStream);

                        byte[] File_Buffer = Binary_Reader.ReadBytes(Posted_File.ContentLength);

                        SampleDb.UploadFiles.Add(new UploadFile

                        {

                            Name=Posted_File.FileName,

                            ContentType=Posted_File.ContentType,

                            Extension=Path.GetExtension(Posted_File.FileName),

                            Size=Posted_File.ContentLength,

                            Content=File_Buffer

                        });

                    }

                }

                SampleDb.SaveChanges();

            }

            GetUploadedFiles();

        }

    }

}

Application Execution

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

<li><a runat="server" href="~/">Home</a></li>

<li><a runat="server" href="~/About">About</a></li>

<li><a runat="server" href="~/Contact">Contact</a></li>

<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.

Up Next
    Ebook Download
    View all
    Learn
    View all