zahed zahed - 3 months ago 25
ASP.NET (C#) Question

Validation for Multiple File upload using asp.net C# web forms

I want to validate multiple uploaded files. It should accept only .png and .jpg files. Below is my code:

protected void uploadFile_Click(object sender, EventArgs e)
{
if (multipleFile.HasFiles)
{
string filenameWithPath = string.Empty;
foreach (HttpPostedFile uploadedFile in multipleFile.PostedFiles)
{
filenameWithPath = System.IO.Path.Combine(
Server.MapPath("~/Uploads/"),
uploadedFile.FileName);
uploadedFile.SaveAs( filenameWithPath );
ltStatusText.Text += "File-<b>"
+ uploadedFile.FileName
+ "</b> uploaded successfully.<br>";
}
}
}

Answer

I got answer.

Below is Design code:

<body>
<form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
    <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="UploadMultipleFiles" />
    <hr />
    <asp:Label ID="Information" runat="server" ForeColor="Green" />
</form>
</body>

Below is 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;
using System.Text.RegularExpressions;

public partial class CS : System.Web.UI.Page
{
 protected void UploadMultipleFiles(object sender, EventArgs e)
 {
  foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
   {
    string fileName = Path.GetFileName(postedFile.FileName);

        Regex reg = new Regex(@"^.*\.(jpg|JPG|jpeg|PNG|png)$");
        if (reg.IsMatch(fileName))
        {
            postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
            Information.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
        }
        else
        {
            Information.Text = "files have been uploaded fail , please check file format!";
        }
    }
   }
  }
Comments