1

I need to validate if a file is an image. Should I check content type or extension? What is more safe / better? I think checking extension is better - what do you think?

string ext = System.IO.Path.GetExtension(fileName).ToLower();
michael
  • 647
  • 2
  • 7
  • 17
  • 2
    Neither, as both are user-supplied. See [Determine if uploaded file is image (any format) on MVC](http://stackoverflow.com/questions/11063900/determine-if-uploaded-file-is-image-any-format-on-mvc). – CodeCaster Jun 24 '14 at 21:25

1 Answers1

2

If all you care for is IMAGE files, then Content-Type is the way to go.

But...

If you DO care for Image type, then you must check by extension, since there really is no true mapping from a content-type to the file extension. For example a content-type of "image/jpeg" could be mapped to either .jpg or .jpeg.

However, if you're talking about checking files uploaded by users, both methods are not safe since they rely on user input. See OWASP: Unrestricted File Upload.

lucidgold
  • 4,432
  • 5
  • 31
  • 51