Multiple Files Upload using JavaScript Dynamic FileUpload Controls

Step 1: Set Web.Config Configurations
<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"
/>


Step2: Add the following code in ur aspx page
<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>


Step3: Place JS in ur ASPX 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>



Step4: Code as Fellow in ur CodeBehind...
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal 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

2 comments:

  1. excellent example..

    ReplyDelete
  2. great. i see this is old, but it provided me with a nice base that actually worked and I was able to build on it easily. thanks.

    ReplyDelete