Introduction

In this blog, I will demonstrate how to validate file upload server side in asp.net.

Step 1

Create an empty ASP.net web application in Visual Studio 2015 or the version of your choice.

Step 2

Right click on the project and add web form and give it a meaningful name.

Step 3

Add the following Bootstrap script and styles cdn link in head section

  1. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
  2. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  3. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>

Step 4

Design web form using file upload control, button control, and bootstrap.

  1. <body>
  2. <form id="form1" runat="server">
  3. <div class="container py-5">
  4. <h4 class="text-center text-uppercase">How to validate file uploader server side in ASP.NET</h4>
  5. <div class="row">
  6. <div class="col-sm-6 col-md-6 col-xs-12">
  7. <div class="form-group">
  8. <label>Choose File:</label>
  9. <div class="input-group">
  10. <div class="custom-file">
  11. <asp:FileUpload ID="FileUpload1" runat="server" CssClass="custom-file-input" />
  12. <label class="custom-file-label"></label>
  13. </div>
  14. <div class="input-group-append">
  15. <asp:Button ID="btnUpload" runat="server" Text="Upload" CssClass="btn btn-secondary" OnClick="btnUpload_Click" />
  16. </div>
  17. </div>
  18. <asp:Label ID="lblMessage" runat="server"></asp:Label>
  19. </div>
  20. </div>
  21. </div>
  22. </div>
  23. </form>
  24. </body

Step 5

Right click on project, and create image folder to upload image.

Step 6

Double click on upload button and write the following code

  1. protected void btnUpload_Click(object sender, EventArgs e)
  2. {
  3. if (FileUpload1.HasFile)
  4. {
  5. string fileExtwnsion = Path.GetExtension(FileUpload1.FileName);
  6. if (fileExtwnsion.ToLower()!=".jpg" && fileExtwnsion.ToLower()!=".png")
  7. {
  8. lblMessage.Text = "Only jpg and png file allowed";
  9. lblMessage.ForeColor = System.Drawing.Color.Red;
  10. }
  11. else
  12. {
  13. int fileSize = FileUpload1.PostedFile.ContentLength;
  14. if (fileSize> 2097152)
  15. {
  16. lblMessage.Text = "Maximum size 2(MB) exceeded ";
  17. lblMessage.ForeColor = System.Drawing.Color.Red;
  18. }
  19. else
  20. {
  21. FileUpload1.SaveAs(Server.MapPath("~/images/" + FileUpload1.FileName));
  22. lblMessage.Text = "File Uploaded successfully";
  23. lblMessage.ForeColor = System.Drawing.Color.Green;
  24. }
  25. }
  26. }
  27. else
  28. {
  29. lblMessage.Text = "File not uploaded";
  30. lblMessage.ForeColor = System.Drawing.Color.Red;
  31. }
  32. }

Step 7

Run project ctrl F5

Screenshot 1

ASP.NET
Screenshot 2
ASP.NET
Screenshot 3
ASP.NET