I've got a simple form:
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype="multipart/form-data" }))
{
<input type="file" name="image" />
<br />
<input type="submit" value="Upload" />
}
which I'm posting to:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
// All necessary validation logic here
}
return RedirectToAction("Index");
}
I'm trying to restrict uploaded files to jpeg, png and gif formats. I wan't to be able to restrict minimum and maximum width and height of the uploaded image as well as image filesize.
I guess I can check the size by simply changing if
statement to:
if (file.ContentLength > 0 && file.ContentLength < maxUploadSize)
I know how to check the extension of the uploaded file but I would prefer to check its mime-type/header as well.
Question:
Given the example code above, how do I properly validate the uploaded file? I want to make sure that the file is:
- a JPEG, GIF or a PNG file (checking file extension and file header)
- not bigger than maximum upload size (file size)
- of dimensions within predefined limit (width/height)