How to check if a file is an image?

Asked

Viewed 681 times

4

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

I’m getting a Multipartfiledata in the back-end.

I’ve tried to check the contenttype of the archive header but, for example, if I change the extension of a text file to image, the contenttype will still show that it is "image/png".

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

  • André, this is [en.so]. Click on [Dit] and translate your question.

  • Hello, you are asking in the OS in Portuguese, try to change the language of your question. In any case, you already have an answer to this in the English OS: https://stackoverflow.com/questions/11063900/determine-if-uploaded-file-is-image-any-format-on-mvc

  • Thanks for the personal help , I will try to replicate the solution presented.

1 answer

5

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

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

    Approach good javeiro, but infallible and very simple.

  • @LINQ programming oriented to Try/catch. Uugh.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.