Get message about asp.net file extension

I keep getting "Only images allowed" and I tried "file.PostedFile.FileName" also did not work !!

this code is written in a separate class.

public static String UploadFile(FileUpload file, String type, out String filename) { String ext = System.IO.Path.GetExtension(file.FileName); filename = ""; if (file.PostedFile.ContentLength > 2000000) { return "File is larger than 2 MB"; } else if (type != "File") { if (ext.ToLower() != ".jpg" || ext.ToLower() != ".png" || ext.ToLower() != ".gif" || ext.ToLower() != ".jpeg") { return "Only images are allowed"; } else { filename = System.IO.Path.GetRandomFileName() + "_" + file.PostedFile.FileName; String root = HttpContext.Current.Server.MapPath("~/Images/"); file.SaveAs(root + type + "/" + filename); return "Success"; } } else { filename = System.IO.Path.GetRandomFileName() + "_" + file.PostedFile.FileName; String root = HttpContext.Current.Server.MapPath("~/Files/"); file.SaveAs(root + filename); return "Success"; } } 
+6
source share
3 answers

Your condition is incorrect, it should look like this:

 if (ext.ToLower() != ".jpg" && ext.ToLower() != ".png" && ext.ToLower() != ".gif" && ext.ToLower() != ".jpeg") { return "Only images are allowed"; } else { ///statement } 

OR

  if (ext.ToLower() == ".jpg" || ext.ToLower() == ".png" || ext.ToLower() == ".gif" || ext.ToLower() == ".jpeg") { ///statement } else { return "Only images are allowed"; } 
+6
source

@volpav's answer will fix your problem, but this great if not the cleanest way to handle this problem.

More elegant would be defining a list of accepted extensions and checking for ext in the list. The advantage of this is that it is easier to maintain if you ever have to change valid types later, and that you can make extensions user-definable if desired.

In the example below, I define a constant (readonly variable) for my class that contains an array with all exceptions, and use the Contains() extension method to check to see if ext exists inside it when checking in UploadFile

 public static readonly string[] VALID_EXTENSIONS = new string[4] { ".png", ".jpg", ".gif", ".jpeg" }; // in UploadFile ... if (!VALID_EXTENSIONS.Contains(ext.ToLower())) { return "Only images are allowed"; } 

By making it static in the code above, I could use this list in the user interface to indicate that it is with the exception of extensions, instead of guessing what is a valid type of image (there are, after all, other types of images than the ones you included).

+4
source

Your condition for validating an extension is logically incorrect (always evaluates to true ). It should be like this ( || is replaced by && ):

 if (ext.ToLower() != ".jpg" && ext.ToLower() != ".png" && ext.ToLower() != ".gif" && ext.ToLower() != ".jpeg") { return "Only images are allowed"; } 
+3
source

Source: https://habr.com/ru/post/955838/


All Articles