I have a controller like this:
public ActionResult Upload (int id, HttpPostedFileBase uploadFile)
{
....
}
How can I make sure that uploadFile is an image (jpg, png etc.)
I have tried with
using (var bitmapImage = new Bitmap (uploadFile.InputStream)) {..}
which throws an ArgumentException if bitmapImage can not be created.
Is there a better way for example by looking at uploadFile.FileName?
You can check the HttpPostedFileBase
object's properties for this
Also here is a small method, I have prepared which you can use/extend...
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...
// linq from Henrik Stenbæk
return formats.Any(item => file.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase));
}
I have also written an article on this here