using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class niunantest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string str = FileUpload1.PostedFile.ContentType;
Response.Write("文件类型:"+str);
string filename = "";
FileExtension[] fe = { FileExtension.GIF, FileExtension.JPG, FileExtension.PNG };
if (FileValidation.IsAllowedExtension(FileUpload1, fe))
{
string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
Response.Write("
验证通过!");
//filename = "/Images/" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt;
//FileUpload1.PostedFile.SaveAs(Server.MapPath(filename));
}
else
{
Response.Write( "
验证不通过,只支持以下格式的图片:JPG,GIF,PNG");
return;
}
}
public enum FileExtension
{
JPG = 255216,
GIF = 7173,
BMP = 6677,
PNG = 13780,
RAR = 8297,
jpg = 255216,
exe = 7790,
xml = 6063,
html = 6033,
aspx = 239187,
cs = 117115,
js = 119105,
txt = 210187,
sql = 255254
}
public class FileValidation
{
public 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;
}
}
}