#region 检测上传真实类型与后缀名是否匹配,是否在允许列表中,允许则上传返回上传路径
public bool IsAllowedExtension(HttpPostedFile hifile,out string upfilepath)
{
bool ret = false;
upfilepath = string.Empty;
string UFileName = hifile.FileName.Trim();//获取文件名
string WebPath = HttpContext.Current.Request.ApplicationPath + "UpLoadFile/FILE/" + System.DateTime.Today.Year.ToString() + "/" + System.DateTime.Today.Month.ToString() + "/"; ;//上传到指定路径
string Exten = Path.GetExtension(hifile.FileName).ToUpper();//获取文件的扩展名
int FileLength = hifile.ContentLength;//文件大小
string FileType = hifile.ContentType.ToUpper();//获取文件的类型
//int fileLengh = hifile.ContentLength;
//byte[] fileByte = new byte[fileLengh];
//Stream fileStream = hifile.InputStream;//建立文件流对象
fileStream.Read(fileByte, 0, fileLengh);
//fileStream.Read(fileByte, 0, 1);
//fileStream.Read(fileByte, 1, 1);
//string fileCode = fileByte[0].ToString() + fileByte[1].ToString();
string fileCode = hifile.InputStream.ReadByte().ToString() + hifile.InputStream.ReadByte().ToString();//文件真实类型代码
if (fileCode != GetFileType(Exten))//判断后缀名返回的代码是否与文件真实类型匹配
{
return false;
}
String[] fileType = { "255216", "7173", "6677", "13780", "8297", "8075", "208207" };//允许上传列表
for (int i = 0; i < fileType.Length; i++)
{
if (fileCode == fileType[i])
{
ret = true;
break;
}
}
if (ret == false) return ret;
if (!Directory.Exists(WebPath))
{
Directory.CreateDirectory(WebPath);
}
string UploadFileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString() + Exten;
upfilepath = WebPath + UploadFileName;
hifile.SaveAs(upfilepath);
//System.IO.FileStream fs = new System.IO.FileStream(upfilepath, 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
//{
// return false;
//}
//r.Close();
//fs.Close();
//if (fileclass != GetFileType(Exten))
//{
// File.Delete(WebPath + UploadFileName);
// ret = false;
//}
//else
//{
// upfilepath = WebPath + UploadFileName;
// ret = true;
//}
return ret;
}
/*文件扩展名说明
*7173 gif
*255216 jpg
*13780 png
*6677 bmp
*239187 txt,aspx,asp,sql
*208207 xls.doc.ppt
*6063 xml
*6033 htm,html
*4742 js
*8075 xlsx,zip,pptx,mmap,zip
*8297 rar
*01 accdb,mdb
*7790 exe,dll
*5666 psd
*255254 rdp
*10056 bt种子
*64101 bat
*/
private string GetFileType(string fileExtenstion)
{
string code =string.Empty;
switch (fileExtenstion)
{
case ".GIF":
code = "7173";
break;
case ".JPG":
code = "255216";
break;
case ".XLS":
code = "208207";
break;
default:
break;
}
return code;
}
#endregion
上传文件检测真实类型
最新推荐文章于 2024-02-06 23:59:27 发布