validate uploaded image wrt size, format in asp.net mvc5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Model argModel, HttpPostedFileBase file)
{
string msg = Utilities.IsImageValid(file);
if (!msg.Trim().Equals("ok"))
{
ModelState.AddModelError("", msg);
}
if (ModelState.IsValid)
{
//saving here
return View("Index");
}
return View("Create", argModel);
}
public class Utilities
{
public static string IsImageValid(object value)
{
var file = value as HttpPostedFileBase;
if (file == null)
{
return "Please attach photograph.";
}
if (file.ContentLength > 1 * 300 * 300)
{
return "Uploaded file size should be less than 1 MB";
}
try
{
using (var img = Image.FromStream(file.InputStream))
{
return img.RawFormat.Equals(ImageFormat.Jpeg) ? "ok" : "Please upload photograph in JPEG/JPG format.";
}
}
catch(Exception ex)
{
return "Unable to validate uploaded image, contact administrator";
}
}
}
[ValidateAntiForgeryToken]
public ActionResult Create(Model argModel, HttpPostedFileBase file)
{
string msg = Utilities.IsImageValid(file);
if (!msg.Trim().Equals("ok"))
{
ModelState.AddModelError("", msg);
}
if (ModelState.IsValid)
{
//saving here
return View("Index");
}
return View("Create", argModel);
}
public class Utilities
{
public static string IsImageValid(object value)
{
var file = value as HttpPostedFileBase;
if (file == null)
{
return "Please attach photograph.";
}
if (file.ContentLength > 1 * 300 * 300)
{
return "Uploaded file size should be less than 1 MB";
}
try
{
using (var img = Image.FromStream(file.InputStream))
{
return img.RawFormat.Equals(ImageFormat.Jpeg) ? "ok" : "Please upload photograph in JPEG/JPG format.";
}
}
catch(Exception ex)
{
return "Unable to validate uploaded image, contact administrator";
}
}
}
Comments
Post a Comment