zoukankan      html  css  js  c++  java
  • ASP.NET通过byte正确安全的判断上传文件格式

    if (Request.Files.Count > 0)
    {
      //这里只测试上传第一张图片file[0]
      HttpPostedFile file0 = Request.Files[0];
         
      //转换成byte,读取图片MIME类型
      Stream stream;
      //int contentLength = file0.ContentLength; //文件长度
      byte[] fileByte = new byte[2];//contentLength,这里我们只读取文件长度的前两位用于判断就好了,这样速度比较快,剩下的也用不到。
      stream = file0.InputStream;
      stream.Read(fileByte, 0, 2);//contentLength,还是取前两位
      stream.Close();
         
      string fileFlag = "";
      if (fileByte != null && fileByte.Length > 0)//图片数据是否为空
      {
        fileFlag = fileByte[0].ToString() + fileByte[1].ToString();         
      }
      string[] fileTypeStr = { "255216", "7173", "6677", "13780" };//对应的图片格式jpg,gif,bmp,png
      if (fileTypeStr.Contains(fileFlag))
      {
        file0.SaveAs(Server.MapPath("~/" + file0.FileName));
      }
      else
      {
        Response.Write("图片格式不正确:" + fileFlag);
      }
    }
  • 相关阅读:
    MyBatis学习记录02篇
    Mybatis学习记录01篇
    项目路径问题
    项目01-JavaWeb网上书城01之工具类
    面试篇01
    创建多线程的方式
    关于web.xml
    快捷键----快速生成未实现的方法
    自动化学习-Day03
    自动化学习-Day02
  • 原文地址:https://www.cnblogs.com/qingjiawen/p/15638665.html
Copyright © 2011-2022 走看看