FileUpload上传文件时获取文件的真实类型

详情见.net上传文件时获取文件的真实类型

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;

}

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,993评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,779评论 18 399
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,554评论 0 17
  • 前言 众所周知,网络游戏中,服务器的搭建尤为重要,无论是授权服务器,还是非授权服务器,它都承担着很大一部分的数据处...
    欣羽馨予阅读 8,484评论 0 24
  • 文/洛落裳
    洛落裳阅读 924评论 40 50