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";
            }
        }
}

Comments

Popular posts from this blog

storing byte array as column value in datatable using c#

post form data and bind with model : using jquery ajax in mvc

Htc sensation XL mobile not working with windows 7 or above, along with Htc sync software