views:

136

answers:

3

While user uploading a file, is it possible to know if the uploaded file is an image or not,

I am open for any solution, Client Side, Server Side or both and we choose based on the case.

+5  A: 

Yes, by checking the magic number of the file.

Alan Haggai Alavi
+2  A: 

May be you can use following code to check if the file is an image.

public bool IsFileAnImage(string filePath)
{
   try
   {
      Image image = Image.FromFile(filePath))
   }
   catch
   {
      return false;   
   }
   finally
   {
      image.Dispose();
   }

   return true;
}
SolutionYogi
A: 

A simple way would be to look at the file's extension.

Steven Sudit
That tells you nothing other than the extension; and is a common way for sites to erroneously allow executables to be uploaded.
Chris Lively
I did say "simple", as opposed to foolproof, but I would suggest that file extension is valuable even if you're concerned that the user would lie. If a user renames virus.exe to funpic.gif, then the extension is making a false promise. However, since it claims to be a gif, we can then test specifically for whether it really is, rejecting it otherwise. Otherwise, we'd have to exhaust all possibilities.
Steven Sudit
I should probably add that renaming the extension can *make* a dangerous file harmless. For example, a `*.VBS` file that destroys the file system is merely interesting reading when renamed to `*.TXT`.
Steven Sudit