I keep getting "Only images are allowed" and I tried "file.PostedFile.FileName" also not working!!
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";
}
}
If filename is empty or null, getExtension(String filename) will return the instance it was given. Otherwise, it returns extension of the filename. To do this it uses the method indexOfExtension(String) which, in turn, uses lastIndexof(char) to find the last occurrence of the '. '.
ASP.NET pages have the extension . aspx, and are normally written in VB (Visual Basic) or C# (C sharp).
Your condition is wrong, it should be like following:
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";
}
@volpav's answer will fix your problem, but that big if
isn't the cleanest way to handle the problem.
More elegant would be to define a list of accepted extensions and check to see if ext
is in the list. The advantages to this would be that it is easier to maintain if you ever have to change the valid types later, and that you can make extensions user definable if that is desirable.
In the example below I am defining a constant (well readonly variable) for my class that contains an array with all exceptions, and use the Contains()
extension method to test to see if ext
exists within it when validating 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 above code, I could use this list in the UI to indicate what are excepted extensions, instead of having the user guess what is a valid image type (There are, after all, other image types than those you have included).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With