0

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>";  
        }  
    }  
}  
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Mr doubt
  • 51
  • 1
  • 10
  • 42
  • See http://stackoverflow.com/a/38790454/5836671 – VDWWD Aug 21 '16 at 21:33
  • HI zahed - can you show us what you've tried so far, and describe what has worked and what hasn't worked yet? – Vince Bowdren Aug 22 '16 at 12:53
  • I have multiple file upload and I want to restrict only uploads jpg or png files and not other extention, googled i did not find any example. @VinceBowdren – Mr doubt Aug 22 '16 at 13:03
  • you just need to take the filename, split the string on the dot (.), get the last part (so the file extension) and check that against a list of your valid file extensions. – ADyson Aug 24 '16 at 13:46

1 Answers1

0

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!";
        }
    }
   }
  }
Mr doubt
  • 51
  • 1
  • 10
  • 42