Saturday, 3 August 2013

Multiple File Upload

Aspx Page
========
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUpload.aspx.cs" Inherits="FileUpload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Multiple FileUploadControl Example</title>
    <script type = "text/javascript">
        var i = 1;
        function AddFile()
        {
             i++;
             var div = document.createElement('DIV');
             div.innerHTML = '<input id="file' + i + '" name = "file' + i + '" type="file" /><img src="Images/delete.jpg" alt="Remove" onclick = "RemoveFile(this)" />';
             document.getElementById("divFile").appendChild(div);           
        }
        function RemoveFile(file)
        {
             document.getElementById("divFile").removeChild(file.parentNode);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data" >
        <div id = "divFile">
            <input id="file1" name = "file1" type="file" />
            <!--FileUpload Controls will be added here -->
        </div>
        <br />
        Add More Files&nbsp; <img src="Images/add.jpg" alt="Add more files" onclick="AddFile()" /><br /><br />
        <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
    </form>
</body>
</html>

.Cs Page
======
    protected void Button1_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("~/Images/") + FileName);
            }
        }
    }