KyLim KyLim - 1 month ago 10
ASP.NET (C#) Question

asp.net dynamic multiple file upload

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);
}
}
}

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


The upload function can dynamic add as much as user want.

<div>
<span style="font-family: Arial">Click to add files</span>
<input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
<div id="FileUploadContainer">
</div>
<asp:Button ID="btnUpload" runat="server"
Text="Upload" OnClick="btnUpload_Click" />

</div>


The problem I'm facing now is when I click upload
for (int i = 0; i < Request.Files.Count; i++)
this line ,
Request.Files.Count always = 0
,even when I have 1 or more file to upload.I tried to debug this
Request.Files.Count 0
always..

Answer

Just wrap your FileUploadContainer div and Upload Button within a form and set its method to POST. Now you should get the files under Request.Files.Count. Just a sample below

<div>
    <span style="font-family: Arial">Click to add files</span>
    <input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
    <form id="frmUploads" runat="server" method="POST">
        <div id="FileUploadContainer">
        </div>
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    </form>
</div>