当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.net判断上传文件类型的三种有效方法

ASP.net判断上传文件类型的三种有效方法

2017年12月12日  | 移动技术网IT编程  | 我要评论
一、安全性比较低,把文本文件1.txt改成1.jpg照样可以上传,但其实现方法容易理解,实现也简单,所以网上很多还是采取这种方法。
复制代码 代码如下:

boolean fileok = false;
string path = server.mappath("~/images/");
//判断是否已经选取文件
if (fileupload1.hasfile)
{
//取得文件的扩展名,并转换成小写
string fileextension = system.io.path.getextension(fileupload1.filename).tolower();
//限定只能上传jpg和gif图片
string[] allowextension = { ".jpg", ".gif" };
//对上传的文件的类型进行一个个匹对
int j = 0;
for (int i = 0; i < allowextension.length; i++)
{
if (fileextension == allowextension[i])
{
fileok = true;
return;
}
else
{
j++;
}
}
if (j > 0)
{
response.write("<script>alert('文件格式不正确');</script>");
return;
}
}
else
{
response.write("<script>alert('你还没有选择文件');</script>");
return;
}
//如果扩展名符合条件,则上传
if (fileok)
{
fileupload1.postedfile.saveas(path + fileupload1.filename);
response.write("<script>alert('上传成功');</script>");
}

二、不检测文件后缀而是检测文件mime内容类型。
复制代码 代码如下:

boolean fileok = false;
string path = server.mappath("~/images/");
//判断是否已经选取文件
if (fileupload1.hasfile)
{
//取得文件mime内容类型
string type = this.fileupload1.postedfile.contenttype.tolower();
if (type.contains("image")) //图片的mime类型为"image/xxx",这里只判断是否图片。
{
fileok = true;
}
else
{
response.write("<script>alert('格式不正确')</script>");
}
}
else
{
response.write("<script>alert('你还没有选择文件');</script>");
}
//如果扩展名符合条件,则上传
if (fileok)
{
fileupload1.postedfile.saveas(path + fileupload1.filename);
response.write("<script>alert('上传成功');</script>");
}

三、可以实现真正意义上的文件类型判断
复制代码 代码如下:

try
{
//判断是否已经选取文件
if (fileupload1.hasfile)
{
if (isallowedextension(fileupload1))
{
string path = server.mappath("~/images/");
fileupload1.postedfile.saveas(path + fileupload1.filename);
response.write("<script>alert('上传成功');</script>");
}
else
{
response.write("<script>alert('您只能上传jpg或者gif图片');</script>");
}
}
else
{
response.write("<script>alert('你还没有选择文件');</script>");
}
}
catch (exception error)
{
response.write(error.tostring());
}
#endregion
}
//真正判断文件类型的关键函数
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;
}
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网