日期:2014-05-17  浏览次数:20352 次

对于上传文件类型的判断
主要是为了防止对于服务器上传马。
网上流传两种一种为后缀名判断,这个没有办法对防止将也改后缀上传。

后一种为取contentType为判断,本人于本地测试,

将某ASP文件后缀改为JPG文件后竟然将其contentType判断为“image/jpeg”

前台代码为
<asp:FileUpload ID="FileUpload1" runat="server" />
  <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
后台代码为

protected void Button1_Click(object sender, EventArgs e)
  {
  Response.Write(FileUpload1.PostedFile.ContentType);
  }

请求一下,有没有其他的确认上传文件类型的方式

------解决方案--------------------
尝试使用Image类加载图片,加载成功后重绘图片
------解决方案--------------------
有是有,不过只能探测已知文件类型也没必要在这种地方浪费资源...

不如对服务器配置完善的安全策略,如严格地权限限制、安装反病毒/反木马等等...
------解决方案--------------------
<asp:RegularExpressionValidator ID="FileValidator" runat="server" ControlToValidate="File1"Display="dynamic" ValidationExpression=".*([\.jpg]|[\.jpeg]|[\.jpe]|[\.gif]|[\.png]|[\.JPEG]|[\.JPG]|[\.GIF]|[\.bmp]|[\.BMP])$" ErrorMessage="jpg,jpeg,jpe,gif,png,JPEG,JPG,GIF,bmp,BMP"></asp:RegularExpressionValidator>
完善系统安全控制
------解决方案--------------------
检测文件类型函数类:
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.IO;
namespace 0x001.Pack
{
public enum FileExtension
{
JPG = 255216,
GIF = 7173,
BMP = 6677,
PNG = 13780
// 255216 jpg;
// 7173 gif;
// 6677 bmp,
// 13780 png;
// 7790 exe dll,
// 8297 rar
// 6063 xml
// 6033 html
// 239187 aspx
// 117115 cs
// 119105 js
// 210187 txt
//255254 sql
}
public class FileValidation
{
static bool IsAllowedExtension() static bool IsAllowedExtension(FileUpload fu, FileExtension[] fileEx)
{
int fileLen = fu.PostedFile.ContentLength;
byte[] imgArray = new byte[fileLen];
fu.PostedFile.InputStream.Read(imgArray, 0, fileLen);
MemoryStream ms = new MemoryStream(imgArray);
System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
string fileclass = "";
byte buffer;
try
{
buffer = br.ReadByte();
fileclass = buffer.ToString();
buffer = br.ReadByte();
fileclass += buffer.ToString();
}
catch
{
}
br.Close();
ms.Close();
foreach (FileExtension fe in fileEx)
{
if (Int32.Parse(fileclass) == (int)fe)
return true;
}
return false;
}
}
}
上传事件判断上传类型
void btnUpload_Click() void btnUpload_Click(object sender, Even