C#检测上传文件真正类型的方法
本文实例讲述了C#检测上传文件真正类型的方法。分享给大家供大家参考。具体分析如下:
对于用户上传的文件如果只是根据扩展名判断,很容易上传上来可执行文件,这是非常危险的,这段代码可以在服务器端检测上传文件的真实类型。
<%@PageLanguage="C#"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<scriptrunat="server">
voidAlert(strings)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(),"js","alert('"+s+"')",true);
}
protectedvoidButton1_Click(objectsender,EventArgse)
{
saveFile();
}
protectedStringsaveFile()
{
StringMaxSize="1024";
//最大文件大小
intimgMaxSize=Convert.ToInt32(MaxSize)*1024*1024;
HttpPostedFileimgFile=FuImg.PostedFile;
if(imgFile==null||FuImg.FileName=="")
{
Alert("请选择文件。");
return"";
}
StringdirPath=Server.MapPath("~/");
stringsaveUrl=Page.ResolveUrl("~/");
if(!System.IO.Directory.Exists(dirPath))
{
Alert("上传目录不存在。");
return"";
}
StringfileName=imgFile.FileName;
StringfileExt=System.IO.Path.GetExtension(fileName).ToLower();
if(imgFile.InputStream==null||imgFile.InputStream.Length>imgMaxSize)
{
Alert("上传文件大小超过限制。");
return"";
}
//验证文件格式
Stringfpath=IsAllowedExtension(imgFile);
if(""==fpath)
{
Alert("图片格式不正确。");
return"";
}
Stringymd=DateTime.Now.ToString("yyyyMMdd",System.Globalization.DateTimeFormatInfo.InvariantInfo);
dirPath+=ymd+"/";
saveUrl=saveUrl+ymd+"/";
//判断目录是否存在
if(!System.IO.Directory.Exists(dirPath))
{
//创建目录
System.IO.Directory.CreateDirectory(dirPath);
}
StringnewFileName=Guid.NewGuid().ToString()+fileExt;
//图片名字
StringfilePath=dirPath+newFileName;
System.IO.File.Move(fpath,filePath);
StringfileUrl=saveUrl+newFileName;
Img.ImageUrl=fileUrl;
//ImageUrl=saveUrl+newFileName;
returnfileUrl;
}
publicStringIsAllowedExtension(HttpPostedFilef)
{
StringnewFile=Server.MapPath("~/"+System.Guid.NewGuid().ToString("D")+".tmp");
f.SaveAs(newFile);
System.IO.FileStreamfs=newSystem.IO.FileStream(newFile,System.IO.FileMode.Open,System.IO.FileAccess.Read);
System.IO.BinaryReaderr=newSystem.IO.BinaryReader(fs);
stringfileclass="";
bytebuffer;
buffer=r.ReadByte();
fileclass=buffer.ToString();
buffer=r.ReadByte();
fileclass+=buffer.ToString();
r.Close();
fs.Close();
/*文件扩展名说明
*7173gif
*255216jpg
*13780png
*6677bmp
*/
Dictionary<String,String>ftype=newDictionary<string,string>();
//添加允许的文件类型
ftype.Add("7173","gif");
ftype.Add("255216","jpg");
ftype.Add("13780","png");
ftype.Add("6677","bmp");
if(ftype.ContainsKey(fileclass))
{
returnnewFile;
}
else
{
System.IO.File.Delete(newFile);
return"";
}
}
</script>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headid="Head1"runat="server">
</head>
<body>
<formid="form1"runat="server">
<asp:FileUploadID="FuImg"runat="server"/>
<asp:ButtonID="Button1"runat="server"
OnClick="Button1_Click"Text="上传测试"/>
<asp:ImageID="Img"runat="server"/>
</form>
</body>
</html>
希望本文所述对大家的C#程序设计有所帮助。