Dynamic File Upload ASP.NET Using JavaScript

Posted On // Leave a Comment

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

ASPX

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

Code Behind

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);
        }
    }
}
download source code :
 source : www.aspsnippets.com

0 komentar: