日期:2014-05-18  浏览次数:20571 次

【求助】如何判断上传文件是否为图片格式???
.net上传图片的时候怎么判断是否为图片格式呢?
如果单纯用扩展名来判断不是很好,因为可以更改扩展名再上传~~~
有没有其他方法~~~~
谢谢

------解决方案--------------------
string type = filename.Substring(filename.LastIndexOf( ". ") + 1);//得到加载文件的扩展名
if (type == "jpg " || type == "bmp " || type == "gif ")
{
.....
}
------解决方案--------------------
有的

private bool IsPicture(string filePath)//filePath是文件的完整路径
{
try
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
string fileClass;
byte buffer;
buffer = reader.ReadByte();
fileClass = buffer.ToString();
buffer = reader.ReadByte();
fileClass += buffer.ToString();
reader.Close();
fs.Close();
if (fileClass == "255216 ")//255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
------解决方案--------------------
1.在web.config中把类型列以下
<add key= "ImgExt " value= "bmp|jpg||gif|png|tif|pcx|wmf|emf|tga|ico|wbmp "/>
2.取得上传文件的扩展名
string strExt = System.IO.Path.GetExtension(postedFile.FileName);
3.判断
if (ConfigurationManager.AppSettings[ "ImgExt "].IndexOf( " " + strExt + " ") > -1)
{
throw new Exception( "上传文件的格式不正确! ");
}

你试试看可以不