3

i'm currently developing a website where the user is able to upload a valid image and not any other file types for security purposes. Atm i have this code but the image extension could still be tampered.

if (extension == ".jpg" || extension == ".jpeg" || extension == ".JPG" || extension == ".gif" || extension == ".png"

Is there any way to make absolutely sure that only these image formats are allowed and that they cannot be altered (like a global code for each format). Thanks

Jack Smith
  • 101
  • 1
  • 1
  • 8

2 Answers2

0

Its better to check on contentType instead of extension.

You can find a pretty comprehensive list here: http://www.freeformatter.com/mime-types-list.html.

A simple check can be done in the following way:

if (myFile.ContentType == "video/mpeg")
{
   // Do your thing
}
else{
   // error
}

If you want to check for more, you can use this for example:

string[] filetypes = { "application/pdf", "image/jpeg", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "text/plain", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel" };
if (!filetypes.Contains(myFile.File.ContentType))
                {
                    //not accepted content type
                }

And you can also check if its an valid image by trying to instantiate a new bitmap

try
{
    using (var bitmap = new System.Drawing.Bitmap(myFile.InputStream))
    {
    }
}
catch (Exception)
{
    return false;
}
Vincentw
  • 164
  • 3
  • 17
  • i have changed the code to if (file.ContentType.ToLower() == "image/jpeg" || file.ContentType.ToLower() == "image/gif" || file.ContentType.ToLower() == "image/png" but by this the user could still convert any other image formats to jpg or so and be accepted by the application – Jack Smith Dec 13 '16 at 15:44
0

Check out this question, I have been using this solution for quite some time now.

Community
  • 1
  • 1
Riwen
  • 4,734
  • 2
  • 19
  • 31