I have a controller like this:
public ActionResult Upload (int id, HttpPostedFileBase uploadFile)
{
....
}
How can I make sure that uploadFile
You could check the file name and extension and MIME type but that might not be reliable because the user could simply rename the file before uploading. Here's a reliable way to achieve that by looking at the contents of the file: https://stackoverflow.com/a/6388927/29407
You could of course extend this to other known image type formats than PNG, like this:
public class ValidateFileAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
var file = value as HttpPostedFileBase;
if (file == null)
{
return false;
}
if (file.ContentLength > 1 * 1024 * 1024)
{
return false;
}
try
{
var allowedFormats = new[]
{
ImageFormat.Jpeg,
ImageFormat.Png,
ImageFormat.Gif,
ImageFormat.Bmp
};
using (var img = Image.FromStream(file.InputStream))
{
return allowedFormats.Contains(img.RawFormat);
}
}
catch { }
return false;
}
}