Introduction
As far as image validation is concerned, three things are most important:
- Aspect ratio
Example: 220 x 110, 310 x 100 (width x height)
- File size
Generally in KB.
- 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
{
var supportedTypes = new[] { "jpg", "jpeg", "png" };
var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);
Image fp = System.Drawing.Image.FromStream(file.InputStream);
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.