Evil 域

当Evil遇上先知

导航

  做了一个上传组件以后,在IE中通过以下代码限制上传文件类型为jpg和png:
 1/// <summary>
 2/// 判断是否合法的文件类型
 3/// </summary>
 4/// <param name="fu">文件上传组件的引用</param>
 5/// <returns>是否允许上传的文件类型</returns>

 6private bool FileTypeAllowed(FileUpload fu)
 7{
 8    //是否合法的文件类型,通过FileUpload的ContentType属性来确定类型
 9    string fileType = fu.PostedFile.ContentType.ToString().ToLower();
10    if (fileType == "image/pjpeg"||fileType == "image/x-png"|| fileType == "image/gif"return true;
11    return false;
12}
  第9行,用来判断文件的mine类型,根据判断结果返回是否允许上传的文件类型。在IE里测试一切正常。但是,到Firefox里上传,则显示为不允许上传的文件类型。原来,在firefox里,jpeg和png图形文件的mine类型表示与IE是有略微差别的,对应关系如下:
IE Firefox
image/pjpeg image/jpeg
image/x-png image/png
  知道了问题,解决方法就很简单了,修改以上代码为:
private bool FileTypeAllowed(FileUpload fu)
{
    
//是否合法的文件类型,通过FileUpload的ContentType属性来确定类型
    string fileType = fu.PostedFile.ContentType.ToString().ToLower();
    
if (fileType == "image/pjpeg"||fileType=="image/jpeg" || fileType == "image/x-png"||fileType=="image/png" || fileType == "image/gif"return true;
    
return false;
}
这样子一来,判断表达式长多了,让人感觉很不爽。要是哪一天有那么十几种文件可以上传,每一种又要适应这两种服务器,那这个表达式的长度岂不是很“可观”?于是,做个小改进吧,把文件名像白名单一样列在一个string[]里,然后,逐个检测,如果不符合,立即返回true;全部检测未找到,则返回false。实现代码如下:
        /// <summary>
        
/// 判断是否合法的文件类型
        
/// </summary>
        
/// <param name="fu">文件上传组件的引用</param>
        
/// <returns>是否允许上传的文件类型</returns>

        private bool FileTypeAllowed(FileUpload fu)
        
{
            
//允许上传的文件类别列表
            string[] allowTypes = new string[]
            
{
                
"image/pjpeg",
                
"image/jpeg",
                
"image/x-png",
                
"image/png",
                
"image/gif"
            }
;
            
            
string fileType = fu.PostedFile.ContentType.ToString().Trim().ToLower();
            
foreach (string allowType in allowTypes)
            
{
                
//找到匹配类型,直接返回真,不再继续找
                if (allowType == fileType) return true
            }

            
//遍历过了,但没有找到此类别,则返回false,不允许上传
            return false;
        }

  以后,再要添加文件类别,只需要在allowTypes这个字符串数组中添加就OK了。