Thursday, December 22

Uploading N number of files by single upload

In this artilce we will discuss how to upload N number of files by single upload. The batch upload feature comes very handy when you have multiple files to upload and user doesn't want to upload one by one.

Batch File Upload
This artilce is tested in IE and chrome, the dispay of input type file is different in IE and chrome.

Let's see how we can achieve above feature of uploading N number of files by single upload button.

Step 1: Add below lines of code in aspx page.
<div>
      
<input type="file" name="attachment" runat="server" id="attachment" onchange="document.getElementById('moreUploadsLink').style.display = 'block';"
/>
      
<input type="hidden" value="0" id="fileCount"
/>
      
<div id
="fileDiv">
      
</div
>
      
<div id="moreUploadsLink" style="display:
none">
            
<a href="javascript:addFile();">Attach another File</a
>
      
</div
>
      
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click"
/></div>

Step 2: Add below javascript in the aspx page, which will give option to add another file and remove file.

<script language='Javascript' type="text/javascript">
      
function
addFile() {
            var ni = document.getElementById("fileDiv"
);
            var objFileCount = document.getElementById("fileCount"
);
            var num = (document.getElementById("fileCount"
).value - 1) + 2;
            objFileCount.value = num;
            var newdiv = document.createElement("div"
);
            var divIdName = "file" + num + "Div"
;
            newdiv.setAttribute("id"
, divIdName);
            newdiv.innerHTML = '<input type="file" name="attachment" id="attachment"/><a href="#" onclick="javascript:removeFile(' + divIdName + ');">Remove </a>'
;
            ni.appendChild(newdiv);
      }

      function
removeFile(divName) {
            var d = document.getElementById("fileDiv"
);
      d.removeChild(divName);

}
</script>

Step 3: Add below lines of code in codebehind file.
protected void btnUpload_Click(object sender, EventArgs e)
{
      HttpFileCollection
uploadFiles = Request.Files;
      for (int
i = 0; i < uploadFiles.Count; i++)
     {
            HttpPostedFile
uploadFile = uploadFiles[i];
            string fileName = Path
.GetFileName(uploadFile.FileName);
            if
(fileName.Trim().Length > 0)
            {
                  uploadFile.SaveAs(Server.MapPath("./Others/"
) + fileName);
            }
      }
}


Step 4: Add method="post" in the form tag. The post tag is used to get the attached file names from input type file.
   <form id="form1" runat="server" method="post">
 
Live Demo

This ends the article of uploading N number of files by single upload.
Like us if you find this post useful. Thanks! 
Shibashish mohanty
Download Code 

No comments:

Post a Comment

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty