我一直得到“只允许图像”,我试过“file.PostedFile.FileName”也不行!
这段代码是在一个单独的类中编写的..
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 (ext.ToLower() != ".jpg" && ext.ToLower() != ".png" && ext.ToLower() != ".gif" && ext.ToLower() != ".jpeg") { return "Only images are allowed"; } else { ///statement }
要么
if (ext.ToLower() == ".jpg" || ext.ToLower() == ".png" || ext.ToLower() == ".gif" || ext.ToLower() == ".jpeg") { ///statement } else { return "Only images are allowed"; }