How to check if a file is an image?

4

I'm working on an application using ASP.NET MVC and AngularJS and need to ensure that the file upload will be just image files, even if someone sends an extension of another type of ".jpg" for example.

I'm getting a MultipartFileData in the backend.

I have tried to check the contentType of the header file, but for example, if I change the length of a text-to-image file, the contentType in> will still show that it is "image / png".

Is there an easier way to ensure that the user only selects and sends true images? (jpeg, jpg, png, bmp, etc.).

    
asked by anonymous 22.06.2017 / 15:37

1 answer

4

Try to open the stream of the file on a Bitmap object. If it works the image is a valid raster content (png, jpg, jpeg, gif and others).

try
{
   var bitmap = Bitmap.FromStream(arquivoRecebido.InputStream);
}
catch 
{
    // Esse aquivo não é uma imagem.
}
    
22.06.2017 / 16:18