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 the limitation of file size. This validates the control before posting back to the Server side and shows the warning message to the end-user using JavaScript.

Steps to Build this Requirement

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

ASP.NET

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

Code Ref

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

namespace FileUploadValidation.Models
{
    public class FileUpload1
    {
        public string ErrorMessage { get; set; }
        public decimal filesize { get; set; }

        public string UploadUserFile(HttpPostedFileBase file)
        {
            try
            {
                var supportedTypes = new[] { "txt", "doc", "docx", "pdf", "xls", "xlsx" };
                var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);
                if (!supportedTypes.Contains(fileExt))
                {
                    ErrorMessage = "File Extension Is InValid - Only Upload WORD/PDF/EXCEL/TXT File";
                    return ErrorMessage;
                }
                else if (file.ContentLength > (filesize * 1024))
                {
                    ErrorMessage = "File size Should Be UpTo " + filesize + "KB";
                    return ErrorMessage;
                }
                else
                {
                    ErrorMessage = "File Is Successfully Uploaded";
                    return ErrorMessage;
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "Upload Container Should Not Be Empty or Contact Admin";
                return ErrorMessage;
            }
        }
    }
}

Code Description

I have declared two variables with different data types.

public string ErrorMessage { get; set; }
public decimal filesize { get; set; }

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

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

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 clients.

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.

var supportedTypes = ["jpg", "jpeg", "png"];

var supportedTypes = ["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”

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

This will fetch the extension of the posted file.

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

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

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

if (!supportedTypes.Contains(fileExt))

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

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

We will check for file size validation.

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

Here, is 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.

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

The filesize value is defined in the controller class file.

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

else
{
    ErrorMessage = "File Is Successfully Uploaded";
    return ErrorMessage;
}

All the above descriptions of code are in the Try {} block.

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

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

 Description

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

Code Ref

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FileUploadValidation.Models;
using System.Web.UI.WebControls;

namespace FileUploadValidation.Controllers
{
    public class FileController : Controller
    {
        // GET: /File/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult fileupload()
        {
            return View();
        }
        [HttpPost]
        public ActionResult fileupload(HttpPostedFileBase file)
        {
            FileUpload1 fs = new FileUpload1();
            fs.filesize = 550;
            string us = fs.UploadUserFile(file);
            if (us != null)
            {
                ViewBag.ResultErrorMessage = fs.ErrorMessage;
            }
            return View();
        }
    }
}

Code Description

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

using FileUploadValidation.Models;

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

[HttpGet]
public ActionResult fileupload()
{
    return View();
}

[HttpPost]
public ActionResult fileupload(HttpPostedFileBase file)
{
    FileUpload1 fs = new FileUpload1();
    fs.filesize = 550;
    string us = fs.UploadUserFile(file);
    if (us != null)
    {
        ViewBag.ResultErrorMessage = fs.ErrorMessage;
    }
    return View();
}

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

public ActionResult fileupload(HttpPostedFileBase file)

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

FileUpload1 fs = new FileUpload1();   

Here, I mentioned the limit of file size.

fs.filesize = 550;

That is 550 KB.

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

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 the model class file.

if (us != null)
{
    ViewBag.ResultErrorMessage = fs.ErrorMessage;
}

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

Error message

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

Code Ref

@model FileUploadValidation.Models.FileUpload1

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

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

<fieldset>
    <legend style="font-family: Arial Black; color: blue">Upload Here</legend>
    <form action="" method="post" enctype="multipart/form-data">
        @if (ViewBag.ResultErrorMessage != null)
        {
            <script type="text/javascript">
                window.onload = function() {
                    alert("@ViewBag.ResultErrorMessage");
                };
            </script>
        }
        <input type="file" name="file" id="file" />
        <p>
            <input type="submit" value="Upload" />
        </p>
    </form>
</fieldset>

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

Code Description

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

@model FileUploadValidation.Models.FileUpload1

Here, I mentioned the title text.

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

The heading text is mentioned here.

<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 the controller class file.

<form action="" method="post" enctype="multipart/form-data">
    @if (ViewBag.ResultErrorMessage != null)
    {
        <script type="text/javascript">
            window.onload = function() {
                alert("@ViewBag.ResultErrorMessage");
            };
        </script>
    }
    <input type="file" name="file" id="file" />
    <p>
        <input type="submit" value="Upload" />
    </p>
</form>

The upload control is defined here.

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

The button controller is used for posting back to the server and checking the validation of uploaded files by the end user.

<p>
    <input type="submit" value="Upload" />
</p>

Here, I used the footer text.

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

Footer text

Step 5. Then, we manually configure settings for MVC URL routing.

Code Ref

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace FileUploadValidation
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "File", action = "fileupload", id = UrlParameter.Optional }
            );
        }
    }
}

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 }

Code Description

OUTPUT

The Url route of this MVC app is.

http://localhost:62152/File/fileupload

The App View Design looks like this.

 View Design

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

 Message

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

Image file

Invalid file

I uploaded one text file without any errors.

 txt file

I uploaded one Excel file without any errors.

Excel file

I uploaded one Word file without any errors.

Word file

I uploaded one PDF file without any errors.

 Pdf file

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

 Valid file

The footer text style shows the date and time.

 Text style

Summary

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


Similar Articles