ASP.NET中如何检测一个图片是否是真实图片 防范病毒上传
主要是用来判断客户端上传的图片是否为真实的图片,以防病毒侵入,保证上传的文件的安全。
主要代码如下:
需要引用
[csharp]
using System.IO;
using System.IO;
[csharp]
public void UploadFile()
{
try
{
HttpPostedFile postfile = Request.Files["file"];
string savepath = Server.MapPath("Image/" + postfile.FileName);
postfile.SaveAs(savepath);
FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
string fileClass;
byte buffer;
byte[] b = new byte[2];
buffer = reader.ReadByte();
b[0] = buffer;
fileClass = buffer.ToString();
buffer = reader.ReadByte();
b[1] = buffer;
fileClass += buffer.ToString();
reader.Close();
fs.Close();
if (fileClass == "255216" || fileClass == "7173" || fileClass == "6677" || fileClass == "13780")
{
//255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
//Response.Write("图片可用");
//保存到数据库中
}
else
{
//Response.Write("图片非法");
File.Delete(savepath); //删除文件
return;
}
}
catch (Exception)
{ //Response.Write("图片非法!");
return;
throw;
}
}
public void UploadFile()
{
try
{
HttpPostedFile postfile = Request.Files["file"];
string savepath = Server.MapPath("Image/" + postfile.FileName);
postfile.SaveAs(savepath);
FileStream fs = new FileStream(savepath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
string fileClass;
byte buffer;
byte[] b = new byte[2];
buffer = reader.ReadByte();
b[0] = buffer;
fileClass = buffer.ToString();
buffer = reader.ReadByte();
b[1] = buffer;
fileClass += buffer.ToString();
reader.Close();
fs.Close();
if (fileClass == "255216" || fileClass == "7173" || fileClass == "6677" || fileClass == "13780")
{
//255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是ra
补充:Web开发 , ASP.Net ,