Thursday, 18 April 2013

how to upload multiple file in asp.net






desing code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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 runat="server">
    <title></title>
</head>
<body>
   <form id="form1" runat="server" enctype="multipart/form-data">
   <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
 
   <p id="upload-area">
  <input id="File1" type="file" runat="server"   />

</p>
<p>
<a href="#" onclick="addTypeFile()">Add another file</a>
</p>
<p><asp:Button ID="btnSubmit" runat="server" Text="Save" Width="80" OnClick="btnSubmit_Click" /></p>
<span id="Span1" runat="server" />
  


<script type="text/javascript">
    function addTypeFile() {
        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 newTypeFile = document.createElement("input");
        newTypeFile.type = "file";


        if (!addTypeFile.lastAssignedId)
            addTypeFile.lastAssignedId = 100;

        newTypeFile.setAttribute("id", "file1" + addTypeFile.lastAssignedId);
        newTypeFile.setAttribute("name", "file1:" + addTypeFile.lastAssignedId);
        uploadArea.appendChild(newTypeFile);
        addTypeFile.lastAssignedId++;
    }
</script>
</form>
</body>
</html>
C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Default2 : System.Web.UI.Page
{
    private String path = String.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        path = Server.MapPath("~/image/");
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        String fileName = String.Empty;
        String ContentType = String.Empty;
        HttpFileCollection uploads = HttpContext.Current.Request.Files;
        for (int i = 0; i < uploads.Count; i++)
        {
            if (uploads[i].FileName.Length == 0)
                continue;
            fileName = Path.GetFileName(uploads[i].FileName);
            try
            {
                uploads[i].SaveAs(path + fileName);
                Span1.InnerHtml = "Save Successful.";
            }
            catch
            {
                Span1.InnerHtml = "Save Failed.";
            }
        }
    }
}

No comments:

Post a Comment