zl程序教程

您现在的位置是:首页 >  后端

当前栏目

ASP.NET在上传文件时对文件类型的高级判断的代码

Net文件ASP上传代码 判断 高级 文件类型
2023-06-13 09:14:15 时间
复制代码代码如下:

usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Collections;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;

publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{

}
protectedvoidbt_upload_Click(objectsender,EventArgse)
{
try
{
if(FileUpload1.PostedFile.FileName=="")
{
this.lb_info.Text="请选择文件!";
}
else
{
stringfilepath=FileUpload1.PostedFile.FileName;
if(IsAllowedExtension(FileUpload1)==true)
{
stringfilename=filepath.Substring(filepath.LastIndexOf("\\")+1);
stringserverpath=Server.MapPath("images/")+filename;
FileUpload1.PostedFile.SaveAs(serverpath);
this.lb_info.Text="上传成功!";
}
else
{
this.lb_info.Text="请上传图片";
}
}
}
catch(Exceptionerror)
{
this.lb_info.Text="上传发生错误!原因:"+error.ToString();
}
}
publicstaticboolIsAllowedExtension(FileUploadhifile)
{
System.IO.FileStreamfs=newSystem.IO.FileStream(hifile.PostedFile.FileName,System.IO.FileMode.Open,System.IO.FileAccess.Read);
System.IO.BinaryReaderr=newSystem.IO.BinaryReader(fs);
stringfileclass="";
bytebuffer;
try
{
buffer=r.ReadByte();
fileclass=buffer.ToString();
buffer=r.ReadByte();
fileclass+=buffer.ToString();

}
catch
{

}
r.Close();
fs.Close();
if(fileclass=="255216"||fileclass=="7173")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
{
returntrue;
}
else
{
returnfalse;
}
}
}

测试通过....