Before reading this article, you might want to know how to code for uploading a file using ASP.NET MVC 3. For this you check my previous post..

Ok, so in this article I’m gonna show how to determine if the file uploaded is an image or not. Now since we use using HttpPostedFileBase, I highly recommend that you read this msdn link, specifically these two properties of the HttpPostedFileBase class.

  • ContentType
  • FileName

Below is a screenshot in the debug mode, where in the action “GetFiles” I have posted a image file as an argument to it. Check out the two properties we talked about earlier.

Here the ContentType property reads “image/png” and the FileName property has the entire file path with the extension.

So keeping these two properties in mind, I have made this method, which you can use (or even extend it) in your project to find out if the file posted is an image or not.

private bool IsImage(HttpPostedFileBase file)  
{  
    if (file.ContentType.Contains("image"))  
    {  
        return true;  
    }

    string[] formats = new string[] { ".jpg", ".png", ".gif", ".jpeg" }; // add more if u like...

    foreach(var item in formats)  
    {  
        if (file.FileName.Contains(item))  
        {  
            return true;  
        }  
    }

    return false;  
}  

Cheers !