c# – 获取发布的文件扩展名asp.net

前端之家收集整理的这篇文章主要介绍了c# – 获取发布的文件扩展名asp.net前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直得到“只允许图像”,我试过“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";
    }

猜你在找的C#相关文章