File Upload Extension Validation In ASP.NET MVC And JavaScript

Introduction

Many times, we are required to upload a file with strongly-typed View and also, apply validation on uploading file using data annotation validators. In this article, I would like to share how we can upload a file and validate that file.

Description

The upload control in MVC checks the file extension as well as limitation of file size. This validates the control before post back to Server side and shows the warning message to end-user using JavaScript .

Steps To Build This Requirement

Step 1

First, create an MVC Empty Template project named as “FileUploadValidation”.

ASP.NET
Step 2

Then, create a Model class file named “FileUpload1.cs”.

Code Ref

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Web;  
  7. namespace FileUploadValidation.Models  
  8. {  
  9.     public class FileUpload1  
  10.     {  
  11.         public string ErrorMessage { get; set; }  
  12.         public decimal filesize { get; set; }  
  13.         public string UploadUserFile(HttpPostedFileBase file)  
  14.         {  
  15.             try  
  16.             {  
  17.                 var supportedTypes = new[] { "txt""doc""docx""pdf""xls""xlsx" };  
  18.                 var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);  
  19.                 if (!supportedTypes.Contains(fileExt))  
  20.                 {  
  21.                     ErrorMessage = "File Extension Is InValid - Only Upload WORD/PDF/EXCEL/TXT File";  
  22.                     return ErrorMessage;  
  23.                 }  
  24.                 else if (file.ContentLength > (filesize * 1024))  
  25.                 {  
  26.                     ErrorMessage = "File size Should Be UpTo " + filesize + "KB";  
  27.                     return ErrorMessage;  
  28.                 }  
  29.                 else  
  30.                 {  
  31.                     ErrorMessage = "File Is Successfully Uploaded";  
  32.                     return ErrorMessage;  
  33.                 }  
  34.             }  
  35.             catch (Exception ex)  
  36.             {  
  37.                 ErrorMessage = "Upload Container Should Not Be Empty or Contact Admin";  
  38.                 return ErrorMessage;  
  39.             }  
  40.         }  
  41.     }  
  42. }  

Code Description

I have declared two variables with different data types.

  1. public string ErrorMessage { get; set; }  
  2. public decimal filesize { get; set; }  

The first one is used to show warning message to the end-user if any fault happens during upload of file by the user.

The second one is to validate the file size if it exceeds.

  1. public string UploadUserFile(HttpPostedFileBase file)  

Then, I created one Definition and inside, I passed one system defined class object called “HttpPostedFileBase”. It serves as the base class for classes that provide access to individual files uploaded by client.

Then, I mentioned some supported extensions. You can add any extension. If you want pdf file validation, then add pdf/doc/docx/xls/xlsx/txt/jpg/jpeg/png in variable supported Types.

  1. var supportedTypes = new[] { "jpg""jpeg""png" };  
  2.   
  3. var supportedTypes = new[] { "txt""doc""docx""pdf""xls""xlsx" };  

First, validate the image extensions like “jpg, jpeg, png” only. Second, validate the file extensions like “txt, doc, docx, pdf, xls,xlsx”

  1. var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);  

This will fetch the extension of posted file.

Here, GetExtension method is used to get the extension of uploaded file that is file.FileName From the path of the system.

  1. if (!supportedTypes.Contains(fileExt))  
  2.                 {  
  3. ErrorMessage = "File Extension Is InValid - Only Upload WORD/PDF/EXCEL/TXT File";  
  4. return ErrorMessage;  
  5.                 }  

Here ,whatever file is uploaded by the user, it can be checked as valid or not by this code.

  1. if (!supportedTypes.Contains(fileExt))  

If it satisfies, it is ok else the error message will be shown to the end-user.

  1. ErrorMessage = "File Extension Is InValid - Only Upload WORD/PDF/EXCEL/TXT File";  
  2. return ErrorMessage;  

We will check for file size validation.

  1. else if (file.ContentLength > (filesize * 1024))  
  2.                 {  
  3.                     ErrorMessage = "File size Should Be UpTo " + filesize + "KB";  
  4.                     return ErrorMessage;  
  5.                 }  

Here, the file.ContentLength gets the length of the file size in bytes.

Then, the filesize * 1024 is the required file size.

If file.ContentLength > filesize * 1024 value will exceed, then the warning message will be generated.

  1. ErrorMessage = "File size Should Be UpTo " + filesize + "KB";  

The filesize value defined in controller class file.

If all conditions are satisfied without any warning messages, then the successful message will come.

  1. else  
  2.                {  
  3.                    ErrorMessage = "File Is Successfully Uploaded";  
  4.                    return ErrorMessage;  
  5.                }  

All above description of code in Try {} block.

If any other warning and validation fail then the catch block will show warning message. Like empty upload control and required extension file’s size more than average.

  1. catch (Exception ex)  
  2.             {  
  3. ErrorMessage = "Upload Container Should Not Be Empty or Contact Admin";                               return ErrorMessage;  
  4.             }  

ASP.NET

Step 3

Then, create a Controller class file named “FileController.cs”.

Code Ref

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using FileUploadValidation.Models;  
  7. using System.Web.UI.WebControls;  
  8.   
  9.   
  10. namespace FileUploadValidation.Controllers  
  11. {  
  12.     public class FileController : Controller  
  13.     {  
  14.         //  
  15.         // GET: /File/  
  16.   
  17.         public ActionResult Index()  
  18.         {  
  19.             return View();  
  20.         }  
  21.         public ActionResult fileupload()  
  22.         {  
  23.             return View();  
  24.         }  
  25.         [HttpPost]  
  26.         public ActionResult fileupload(HttpPostedFileBase file)  
  27.         {  
  28.             FileUpload1 fs = new FileUpload1();  
  29.             fs.filesize = 550;  
  30.             string us = fs.UploadUserFile(file);  
  31.             if (us != null)  
  32.             {  
  33.                 ViewBag.ResultErrorMessage = fs.ErrorMessage;  
  34.             }  
  35.             return View();  
  36.         }  
  37.     }  
  38. }  

Code Description

Here, I used the reference of Model class file for future one.

  1. using FileUploadValidation.Models;   

Here, I used Controller action method named “fileupload”.One for [HttpGet] and another for [HttpPost] attributes. 

  1. [HttpGet]  
  2. public ActionResult fileupload()  
  3.         {  
  4.             return View();  
  5.         }  
  6. [HttpPost]  
  7. public ActionResult fileupload(HttpPostedFileBase file)  
  8.         {  
  9.             FileUpload1 fs = new FileUpload1();  
  10.             fs.filesize = 550;  
  11.             string us = fs.UploadUserFile(file);  
  12.             if (us != null)  
  13.             {  
  14.                 ViewBag.ResultErrorMessage = fs.ErrorMessage;  
  15.             }  
  16.             return View();  
  17.         }   

Here, I passed the class as earlier discussed on model class.

  1. public ActionResult fileupload(HttpPostedFileBase file)   

Here, I use the model class file object to inherits the properties.

  1. FileUpload1 fs = new FileUpload1();   

Here, I mentioned the limit of file size .

  1. fs.filesize = 550;   

That is 550 KB .

Here, I used the Model class function by passing base class object.

  1. string us = fs.UploadUserFile(file);   

If the uploaded value is not empty or null, then all warnings and successful messages will come in other ways in all validation messages as defined in model class file. 

  1. if (us != null)  
  2.             {  
  3.                 ViewBag.ResultErrorMessage = fs.ErrorMessage;  
  4.             }   

Here, error message variable value is assigned to viewbag type that will pass value from controller to view using @ symbol.

ASP.NET

Step4

Then, create one View named “fileupload.cshtml” inside "~\Views\File\fileupload.cshtml" .

Code Ref 

  1. @model FileUploadValidation.Models.FileUpload1  
  2.   
  3. @{  
  4.     ViewBag.Title = "Satyaprakash File Upload";  
  5. }  
  6. <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">SATYA'S WORD/PDF/EXCEL/TXT UPLOAD FILE VALIDATION</h2>  
  7.   
  8. <fieldset>  
  9.     <legend style="font-family:Arial Black;color:blue">Upload Here</legend>  
  10.     <form action="" method="post" enctype="multipart/form-data">  
  11.         @if (ViewBag.ResultErrorMessage != null)  
  12.         {  
  13.             <script type="text/javascript">  
  14.     window.onload = function () {  
  15.         alert("@ViewBag.ResultErrorMessage");  
  16.        };  
  17.             </script>  
  18.         }  
  19.         <input type="file" name="file" id="file " />  
  20.         <div>  
  21.             <input type="submit" value="Upload" />  
  22.         </div>  
  23.     </form>  
  24. </fieldset>  
  25.   
  26. <footer>  
  27.     <p style="background-color: Yellow; color: Blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  28. </footer>   

Code Description

Here, I used model class file reference to access properties , message and function validation through base class object.

  1. @model FileUploadValidation.Models.FileUpload1   

Here, I mentioned title text. 

  1. @{  
  2.     ViewBag.Title = "Satyaprakash File Upload";  
  3. }   

The heading text is mentioned here.

  1. <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">SATYA'S WORD/PDF/EXCEL/TXT UPLOAD FILE VALIDATION</h2>   

Then, I used viewbag validation messages using javascript as defined earlier in controller class file. 

  1. <form action="" method="post" enctype="multipart/form-data">  
  2.         @if (ViewBag.ResultErrorMessage != null)  
  3.         {  
  4.             <script type="text/javascript">  
  5.     window.onload = function () {  
  6.         alert("@ViewBag.ResultErrorMessage");  
  7.        };  
  8.             </script>  
  9.         }  
  10.         <input type="file" name="file" id="file " />  
  11.         <div>  
  12.             <input type="submit" value="Upload" />  
  13.         </div>  
  14.     </form>   

The upload control is defined here.

  1. <input type="file" name="file" id="file " />   

The button controller used for post back to server and check validation of uploaded file by the end user. 

  1.  <div>  
  2.   <input type="submit" value="Upload" />  
  3. </div>   

Here, I used the footer text . 

  1. <footer>  
  2.     <p style="background-color: Yellow; color: Blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  3. </footer>  

ASP.NET

Step5

Then, we manually configure settings for MVC url routing.

Code Ref 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace FileUploadValidation  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16.             routes.MapRoute(  
  17.                 name: "Default",  
  18.                 url: "{controller}/{action}/{id}",  
  19.                 defaults: new { controller = "File", action = "fileupload", id = UrlParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  
  23. }   

Code Description

Here, I mentioned my Controller name and Controller action method name to configure settings for MVC url routing.

defaults: new { controller = "File", action = "fileupload", id=UrlParameter.Optional }

ASP.NET

OUTPUT

The Url route of this MVC app is:

http://localhost:62152/File/fileupload

The App View Design looks like this.

ASP.NET

Here no file is uploaded So, The Message will come like this.

ASP.NET

Here I uploaded one image file , The invalid file extension message will come.

ASP.NET

ASP.NET

I uploaded one txt file with out any error.

ASP.NET

I uploaded one Excel file with out any error.

ASP.NET

I uploaded one Word file with out any error.

ASP.NET

I uploaded one Pdf file with out any error.

ASP.NET

I uploaded one valid file extension but beyond the size limits.

ASP.NET

The footer text style shows the date  and time.

ASP.NET

Summary

  1. Create valid file or supported file extensions only for upload and end user requirement.
  2. Validation for the valid file extensions.
  3. Validation for the invalid file extensions.