ASP.NET在上传文件时对文件类型的高级判断的代码
程序员文章站
2024-03-09 10:08:41
复制代码 代码如下: using system; using system.data; using system.configuration; using system.c...
复制代码 代码如下:
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;
}
}
}
测试通过....