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?
Or you can check it on client side thru html attribute 'accept' to filter the file asap:
this will only show filetypes defined in your accept attribute as default. Beware, user can still change filetye to "All files", with this in mind, better check this:
Solved concern , a javascript snippet to check extension, and then do some editing to disable button like:
until file extension is correct. nevertheless have it checked on server side. :)
You can check the
HttpPostedFileBase
object's properties for thisAlso here is a small method, I have prepared which you can use/extend...
I have also written an article on this here
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: