Uploading Multiple Files by Dynamically generated FileUpload Control in c#.Net

Uploading Multiple Files by Dynamically generated FileUpload Control in c#.Net 

Introduction

In web application we generally need to upload multiple files at a time. Here in this example we will dynamically decide and generate FileUpload Control to browse number of files we need to upload on server.

We have also put validation on File Upload:

1.      Empty file Check (Length=0)

2.      Limiting maximum size of File to upload.

3.      Type of file to upload.

 

JavaScript  for Multiple FileUpload Control. Add this in the Head Tag of Source Page.

<script type = "text/javascript">

    var counter = 0;

    function AddFileUpload() {

 

 

        var div = document.createElement('DIV');

        div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +

                     '" type="file" />' +

                     '<input id="Button' + counter + '" type="button" ' +

                     'value="Remove" onclick = "RemoveFileUpload(this)" />';

 

 

        document.getElementById("FileUploadContainer").appendChild(div);

        counter++;

    }

 

 

    function RemoveFileUpload(div) {

        document.getElementById("FileUploadContainer").removeChild(div.parentNode);

 

 

    }

</script>

............................................................................................................................................

Complete Source Code of HTML Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<HTML xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Multiple Files Upload</title>

<script type = "text/javascript">

    var counter = 0;

    function AddFileUpload() {

    var div = document.createElement('DIV');

    div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +

     '" type="file" />' +

      '<input id="Button' + counter + '" type="button" ' +

      'value="Remove" onclick = "RemoveFileUpload(this)" />';

        document.getElementById("FileUploadContainer").appendChild(div);

        counter++;

    }

function RemoveFileUpload(div) {

        document.getElementById("FileUploadContainer").removeChild(div.parentNode);

}

</script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <asp:Label ID="lblError" runat="server" Font-Bold="true" ForeColor="Red"> </asp:Label><br />

  <span style="font-family:Arial"><span style="color: #003366">&nbsp;Click to add files</span></span>

 <input id="Button1" onclick="AddFileUpload()" 

 style="height: 27px; width: 74px;" tabindex="25" type="button" value="add" /><br /> <br /><br />

  <div id="FileUploadContainer">

  <asp:FileUpload ID="FileUpload1" runat="server" />

  <!--FileUpload Controls will be added here -->

                                                                                          </div>                                                                                         <br />                                                                                         <br />                                                                                          <br />

<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />

<br /><br /></TD>

    </div>

    </form>

</body>

</html>

.............................................................................

The complete code of Default.aspx.cs  Page

using System;

using System.Web;

using System.Collections.Generic;

using System.Linq;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

using System.Data;

using System.Text;

using System.IO;

 

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

{

string error;

protected void Page_Load(object sender, EventArgs e)

    {

     if (IsPostBack)

        {

         error="";

        }

    }

 protected void btnUpload_Click(object sender, EventArgs e)

 {

string FileName="";

        try

        {  // Get the HttpFileCollection

           HttpFileCollection hfc = Request.Files;

           for (int i = 0; i < hfc.Count; i++)

           {

           HttpPostedFile hpf = hfc[i];

           FileName = System.IO.Path.GetFileName(hpf.FileName);

           if (hpf.ContentLength > 0)

           {

           if (hpf.ContentLength < 307200)

           {

           string Ext = System.IO.Path.GetExtension(hpf.FileName);

           if ((Ext == ".txt") || (Ext == ".doc") || (Ext == ".docx") || (Ext == ".xls") || (Ext == ".xlsx"))

           {

           hpf.SaveAs(Server.MapPath("~/Files/") + "doc[" + (i + 1).ToString() + "]@" + System.DateTime.Now.Date.Date.ToString("dd-MM-yy") + Ext);

           error = "'" + FileName.ToString() + "'" + " Uploaded Successfully..." + "<br>";

           }

else

           {

           error = "'" + FileName.ToString() + "'" + " Failed :" + "'" + Ext.ToString() + "'" + " Extension not supported... " + "<br>";

            }

         }

       

 

else

          {

           error = "'" + FileName.ToString() + "'" + " Failed : " + " file length should not exceed 3MB... " + "<br>";

           }

          }

          else

          {

          error = "'" + FileName.ToString() + "'" + " Failed : " + " File is Empty... " + "<br>";

          }

          lblError.Text = error + lblError.Text;

          }

      }

      catch (Exception ex)

        {

            Response.Write(ex.Message);

        }

    }

}