Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How To Do Custom Image Validation In ASP.NET MVC?

0.00/5 (No votes)
2 Oct 2014 1  
Custom image validation method in MVC which is useful for validating images in web.

Introduction

As far as image validation is concerned, three things are most important:

  1. Aspect ratio

    Example: 220 x 110, 310 x 100 (width x height)

  2. File size

    Generally in KB.

  3. File Extension

    jpg, png, jpeg, gif...

Background

Basic MVC knowledge is required for using this method.

Using the Code

First of all, we want the height and width of a specific image, so add the reference System.Drawing assembly and add the class file FileUpload.cs in model folder.

Point to be noted that my project name is TestProject.

using System.Drawing;

namespace TestProject.Models
{
    public class FileUpload
    {
        public string getseterror { get; set; }

        public int ar { get; set; }

        public decimal filesize { get; set; }
        
        public string UploadUserFile(HttpPostedFileBase file)
        {
            try
            {
                // supported extensions
                // you can add any of extension,if you want pdf file validation then add .pdf in 
                // variable supportedTypes.
            
                var supportedTypes = new[] { "jpg", "jpeg", "png" };

                // following will fetch the extension of posted file.

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

                // Image datatype is included in System.Drawing librery.will get the image properties 
                //  like height, width.

                Image fp = System.Drawing.Image.FromStream(file.InputStream);

                //variable will get the ratio of image 
                // (600 x 400),ratio will be 1.5 

                decimal fu = ((decimal)fp.Width / fp.Height);

                if (file.ContentLength > (filesize*1024))
                {
                    getseterror = "filesize will be upto "+filesize+"KB";
                    return getseterror;                    
                }
                else if (!supportedTypes.Contains(fileExt))
                {
                    getseterror = "file extension is not valid";
                    return getseterror;
                }
                else if (fu != ar)
                {
                    getseterror = "file should be in mentioned aspect ratio";
                    return getseterror;       
                }
                else
                {
                    getseterror = "success";
                    return getseterror;
                }
            }
            catch (Exception ex)
            {
                getseterror = ex.Message;
                return getseterror;
            }
         }
    }
}

Now look at the FileUpload class, we have created method UploadUserFile.

Now it's time to call this method in controller part:

public ActionResult fileupload()
{
    return View();
}
[HttpPost]
public ActionResult fileupload(HttpPostedFileBase file)
{
    FileUpload fs = new FileUpload();
    fs.ar = 2;
    fs.filesize = 10;
    string us = fs.UploadUserFile(file);
    if (us != null)
    {
        ViewBag.ResultMessage = fs.getseterror;
    }
    return View();
}

We have set the aspect ratio to 2, so the valid images are of 200 x 100, 400 x 200, etc.

Size of image will be 10 KB.

Let's move to the view part....

@{
    ViewBag.Title = "fileupload";
}
<html>
<head>
<title>Image Validation</title>
</head>
<body>
<h2>fileupload</h2>
    <form action="" method="post" enctype="multipart/form-data">
        <div class="message-success">@ViewBag.ResultMessage</div>
        <input type="file" name="file" id="file " />
         <div>
            <input type="submit" value="Upload" />
        </div>
    </form>
</body>
</html>

Note: You have to make respective changes while using this method.

Points of Interest

I faced some problems to fetch the aspect ratio of images, but finally I got it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here