Wednesday, September 1, 2010

Multiple File Uploads

If you want to add multiple File Upload controls on demand, you will need a Javascript code to add the controls. The form could look like this:

<form id="form1" runat="server" enctype="multipart/form-data">

Here is a sample Javascript code that accomplishes the job:

<script type="text/javascript">
function addFileUploadBox()
{
      if(! document.getElementById || !document.createElement)
      {
            return false;
      }
      var uploadArea = document.getElementById("upload-area");
      if(!uploadArea)
      {
            return;
      }
      var newLine = document.createElement("br");
      uploadArea.appendChild(newLine);
      var newLine = document.createElement("br");
      uploadArea.appendChild(newLine);
      var newUploadBox = document.createElement("input");
      newUploadBox.type = "file";
      newUploadBox.size = "60";
      if(!addFileUploadBox.lastAssignedId)
            addFileUploadBox.lastAssignedId = 100;
      newUploadBox.setAttribute("id","FileField" +    addFileUploadBox.lastAssignedId);
      newUploadBox.setAttribute("name","FileField" + addFileUploadBox.lastAssignedId);
      uploadArea.appendChild(newUploadBox);
      addFileUploadBox.lastAssignedId++;
}
</script>

In code behind, you need to iterate through the Files property of the Request object. It is an HttpFileCollection:

HttpFileCollection uploads = HttpContext.Current.Request.Files;
for (int i = 0; i < uploads.Count; i++)
{
      if (uploads[i].ContentLength > 0)
      {
            string c = Path.GetFileName(uploads[i].FileName);
            try
            {
                  string path = MapPath("uploads/") + c;
                  FileField.PostedFile.SaveAs(path);
            }
            catch{}
      }
}

No comments:

Post a Comment