判断上传文件是否是图片文件

方法一:用image对象判断是否为图片

/// <summary>
/// 判断文件是否为图片
/// </summary>
/// <param name="path">文件的完整路径</param>
/// <returns>返回结果</returns>
public Boolean IsImage(string path)
{
try
{
 System.Drawing.Image img = System.Drawing.Image.FromFile(path);
 return true;
}
catch (Exception e)
{
 return false;
}
}

方法二,判断文件头

/// <summary>
/// 根据文件头判断上传的文件类型
/// </summary>
/// <param name="filePath">filePath是文件的完整路径 </param>
/// <returns>返回true或false</returns>
private bool IsPicture(string 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" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677")
 //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
 {
 return true;
 }
 else
 {
 return false;
 }
}
catch
{
 return false;
}
}
public enum FileExtension
{
    JPG = 255216,
    GIF = 7173,
    BMP = 6677,
    PNG = 13780,
    COM = 7790,
    EXE = 7790,
    DLL = 7790,
    RAR = 8297,
    ZIP = 8075,
    XML = 6063,
    HTML = 6033,
    ASPX = 239187,
    CS = 117115,
    JS = 119105,
    TXT = 210187,
    SQL = 255254,
    BAT = 64101,
    BTSEED = 10056,
    RDP = 255254,
    PSD = 5666,
    PDF = 3780,
    CHM = 7384,
    LOG = 70105,
    REG = 8269,
    HLP = 6395,
    DOC = 208207,
    XLS = 208207,
    DOCX = 208207,
    XLSX = 208207,
}

据说方法二针对常规修改的木马有效,也就是直接修改扩展名的,比如把.asp改成.jpg这种。但是对于那种用工具生成的jpg木马没有效果。推荐大家用第一种好了。

 

 

 

 

主要代码如下:
 
需要引用
 
[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是rar
                    //Response.Write("图片可用");
                    //保存到数据库中
                }
                else
                {
                    //Response.Write("图片非法");
                    File.Delete(savepath); //删除文件
                    return;
                }
            }
            catch (Exception)
            { //Response.Write("图片非法!");
                return;
                throw;
            }
}

MVC 中的代码如下,在这里我返回的JSON格式,当然可以返回Content或其他: [csharp]
/// <summary> /// 上传头像 /// </summary> /// <param name="userId">用户编号</param> /// <returns>Json(-1表示系统异常,-2表示文件不合法)</returns> [HttpPost] public JsonResult UploadAvatar(string userId) { //上传头像 string folderPath = "/upload/avatar/"; //判断路径是否存在 if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath);//创建文件路径 HttpPostedFileBase uploadFile = Request.Files["avatars"]; if (uploadFile != null) { string oriFileName = uploadFile.FileName;//原始文件名 string fileName = userId + "_" + oriFileName; uploadFile.SaveAs(Server.MapPath(folderPath + fileName)); FileStream fs = new FileStream(Server.MapPath(folderPath + fileName), 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("图片非法"); FileInfo f = new FileInfo(Server.MapPath(folderPath + fileName)); f.Delete(); //删除文件 return Json(-2, JsonRequestBehavior.AllowGet); } return Json(Server.HtmlEncode(folderPath + fileName), JsonRequestBehavior.AllowGet); } return Json(-1, JsonRequestBehavior.AllowGet); } /// <summary> /// 上传头像 /// </summary> /// <param name="userId">用户编号</param> /// <returns>Json(-1表示系统异常,-2表示文件不合法)</returns> [HttpPost] public JsonResult UploadAvatar(string userId) { //上传头像 string folderPath = "/upload/avatar/"; //判断路径是否存在 if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath);//创建文件路径 HttpPostedFileBase uploadFile = Request.Files["avatars"]; if (uploadFile != null) { string oriFileName = uploadFile.FileName;//原始文件名 string fileName = userId + "_" + oriFileName; uploadFile.SaveAs(Server.MapPath(folderPath + fileName)); FileStream fs = new FileStream(Server.MapPath(folderPath + fileName), 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("图片非法"); FileInfo f = new FileInfo(Server.MapPath(folderPath + fileName)); f.Delete(); //删除文件 return Json(-2, JsonRequestBehavior.AllowGet); } return Json(Server.HtmlEncode(folderPath + fileName), JsonRequestBehavior.AllowGet); } return Json(-1, JsonRequestBehavior.AllowGet); }

 

转载于:https://www.cnblogs.com/Violety/p/11345910.html

  • 0
    点赞
  • 0
    收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值