Pages

Thursday, May 24, 2012

Uploading Multiple Files using JavaScript Dynamic FileUpload Controls in ASP.Net

Abstract: Here Mudassar Ahmed Khan has explained how to upload multiple files by dynamically adding or removing FileUpload controls using JavaScript in ASP.Net 



In this article I am explaining how to upload multiple files by dynamically adding FileUpload controls using JavaScript.
Here I will explain how one can create a multiple file uploading controls in a very simple manner and very less amount of code. With this example one will able to perform the following functions
1. Add FileUpload Controls dynamically using JavaScript
2. Remove FileUpload Controls dynamically using JavaScript.
Since I am using JavaScript the UI becomes elegant since no need of postback or AJAX to add or remove FileUpload Controls.

Adding and Removing FileUpload Controls using JavaScript
Below is the HTML markup of the page. As you can see I have added a HTML button in order to add new FileUpload Controls, a DIV FileUploadContainer in which the dynamic FileUpload Controls will be added and a ASP.Net Upload Button in order to upload the files when the Upload Button us clicked.
An important think to note that you will need to add enctype="multipart/form-data to the form in order to allow the uploading of files through dynamic FileUpload controls.
<form id="form1" runat="server" enctype="multipart/form-data" method = "post">
    <span style ="font-family:Arial">Click to add files</span>&nbsp;&nbsp;
    <input id="Button1" type="button" value="add" onclick = "AddFileUpload()" />
    <br /><br />
    <div id = "FileUploadContainer">
        <!--FileUpload Controls will be added here -->
    </div>
    <br />
    <asp:Button ID="btnUpload" runat="server"
      Text="Upload" OnClick="btnUpload_Click" />
</form>

Now in order to add and remove the FileUpload Controls dynamically here is the JavaScript functions that are used.

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

As you will notice above first I am creating a DIV element and then adding a HTML FileUpload Control along with a HTML Button in order to remove the FileUpload Controls. Also onclick of the Remove button I am calling the RemoveFileUpload function which removes the dynamically created FileUpload control.

Server Side Uploading of Files
Server Side I have written the following code in the Click event of the Upload Button
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        HttpPostedFile PostedFile = Request.Files[i];
        if (PostedFile.ContentLength > 0)
        {
            string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
            PostedFile.SaveAs(Server.MapPath("Files\\") + FileName);
        }
    }
}


VB.Net
Protected Sub btnUpload_Click(ByVal sender As ObjectByVal e As System.EventArgs)
  For i As Integer = 0 To Request.Files.Count - 1
   Dim PostedFile As HttpPostedFile = Request.Files(i)
   If PostedFile.ContentLength > 0 Then
      Dim FileName As String = System.IO.Path.GetFileName(PostedFile.FileName)
      PostedFile.SaveAs(Server.MapPath("Files\") + FileName)
   End If
  Next
End Sub

In the above code snippet I am simply looping through the Request.Files Collection which contains the uploaded Files and then I am saving each of them one by one in a Folder called Files within my website root folder.

Web.Config Configurations
Since this article deals with uploading multiple files it is important to discuss the maximum file size allowed. By default ASP.Net allows files of size maximum 4MB at a time. Hence in order to upload more data we will need to increase this limit. Refer the httpRuntimesection of the Web.Config, if it is not present in your Web.Config you can simply paste the one given below in your file.
<httpRuntime
  executionTimeout="110"
  maxRequestLength="4096"
  requestLengthDiskThreshold="80"
  useFullyQualifiedRedirectUrl="false"
  minFreeThreads="8"
  minLocalRequestFreeThreads="4"
  appRequestQueueLimit="5000"
  enableKernelOutputCache="true"
  enableVersionHeader="true"
  requireRootedSaveAsPath="true"
  enable="true"
  shutdownTimeout="90"
  delayNotificationTimeout="5"
  waitChangeNotification="0"
  maxWaitChangeNotification="0"
  enableHeaderChecking="true"
  sendCacheControlHeader="true"
  apartmentThreading="false"
/>

In order to increase the maximum file size limit you will need to change the value of the maxRequestLength attribute in kilobytes (KB). For example if you want to set the upload limit to 10 MB you will have to set the value to 10240. Another important parameter isexecutionTimeout. It determines the maximum amount of time in seconds ASP.Net will process the request and after which it will stop the processing. By default the value is 110 seconds. You can modify it to the value that suits your needs

Multiple FileUploads using JavaScript

The above code has been tested in the following browsers

Internet Explorer  FireFox  Chrome  Safari  Opera 
* All browser logos displayed above are property of their respective owners.
With this the article comes to an end. Download the related sample source code in VB.Net and C# using the link below.

No comments:

Post a Comment