michael
michael

Reputation: 647

file validation - content type or extension?

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();

Upvotes: 1

Views: 2407

Answers (1)

lucidgold
lucidgold

Reputation: 4542

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.

Upvotes: 2

Related Questions