Check if file is uploaded in C # ASP.NET MVC

I have a controller

[HttpPost] public ActionResult ChangeAvatar(HttpPostedFileBase file) { AvatarHelper.AvatarUpdate(file, User.Identity.Name); return RedirectToAction("Index", "Profile"); } 

And I already check if the file is in jpeg / png format:

 private static bool IsImage(string contentType) { return AllowedFormats.Any(format => contentType.EndsWith(format, StringComparison.OrdinalIgnoreCase)); } public static List<string> AllowedFormats { get { return new List<string>() {".jpg", ".png", ".jpeg"}; } } 

What I need is to ensure that the downloaded file is a real image file, not a txt file with an image extension.

I convert my downloaded file as follows:

 using (var image = System.Drawing.Image.FromStream(postedFile.InputStream)) { ///image stuff } 

I am thinking of a try / catch block to create an image from an input stream, but I am wondering if it has a good way? Thanks)

PS

I wonder if there is another (more efficient way that tries to / catch the block) to check if the file is a real way?

+6
source share
2 answers

You can use the RawFormat property:

 private static ImageFormat[] ValidFormats = new[] { ImageFormat.Jpeg, ImageFormat.Png }; public bool IsValid(Stream image) { try { using (var img = Image.FromStream(file.InputStream)) { return ValidFormats.Contains(img.RawFormat); } } catch { return false; } } 

You can also put this validation logic in the reusable validation attribute, as shown in this post .

+4
source

My solution is as an extension, actually checking if the base64 string is an image or not:

 public static bool IsImage(this string base64String) { byte[] imageBytes = Convert.FromBase64String(base64String); var stream = new MemoryStream(imageBytes, 0, imageBytes.Length); try { stream.Write(imageBytes, 0, imageBytes.Length); System.Drawing.Image image = System.Drawing.Image.FromStream(stream, true); return true; } catch (Exception) { return false; } } 

Using:

 if(!"base64string".IsImage()) throw new Exception("Not an image"); 
+2
source

All Articles