网络编程 
首页 > 网络编程 > 浏览文章

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

(编辑:jimmy 日期: 2024/10/19 浏览:3 次 )
复制代码 代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void bt_upload_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.PostedFile.FileName == "")
{
this.lb_info.Text = "请选择文件!";
}
else
{
string filepath = FileUpload1.PostedFile.FileName;
if (IsAllowedExtension(FileUpload1) == true)
{
string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
string serverpath = Server.MapPath("images/") + filename;
FileUpload1.PostedFile.SaveAs(serverpath);
this.lb_info.Text = "上传成功!";
}
else
{
this.lb_info.Text = "请上传图片";
}
}
}
catch (Exception error)
{
this.lb_info.Text = "上传发生错误!原因:" + error.ToString();
}
}
public static bool IsAllowedExtension(FileUpload hifile)
{
System.IO.FileStream fs = new System.IO.FileStream(hifile.PostedFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
string fileclass = "";
byte buffer;
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
{
return true;
}
else
{
return false;
}
}
}

测试通过....
上一篇:JQuery运用ajax注册用户实例(后台asp.net)
下一篇:Asp.Net Oracle数据的通用操作类
一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 SiteMap