最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

.net文件上傳時(shí)實(shí)現(xiàn)通過文件頭確認(rèn)文件類型的方法

 更新時(shí)間:2014年07月24日 10:57:19   投稿:shichen2014  
這篇文章主要介紹了.net文件上傳時(shí)實(shí)現(xiàn)通過文件頭確認(rèn)文件類型的方法,很實(shí)用的功能,需要的朋友可以參考下

本文實(shí)例講述了.net文件上傳時(shí)實(shí)現(xiàn)通過文件頭確認(rèn)文件類型的方法,其中 script 用來返回給頁面的數(shù)據(jù),讀者還可以根據(jù)自身需要對相關(guān)部分自行修改。另外,文件頭也可以自行添加定義。

主要代碼如下:

AppCode/FileUpload.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

/// <summary>
/// FileHeader 的摘要說明
/// </summary>
public static class FileUpload
{
  private static string script = string.Empty;
  private static bool autonamed = true;
  private static Random ra = new Random();

  public static bool AutoNamed
  {
    get
    {
      return autonamed;
    }
    set
    {
      autonamed = value;
    }
  }
  public static string Script
  {
    get
    {
      return "var upload = [" + script + "];";
    }
  }
  public static Dictionary<string, byte[]> ImageHeader = new Dictionary<string, byte[]>();
  public static Dictionary<string, object> FilesHeader = new Dictionary<string, object>();
  
  static FileUpload()
 {
    ImageHeader.Add("gif", new byte[] { 71, 73, 70, 56, 57, 97 });
    ImageHeader.Add("bmp", new byte[] { 66, 77 });
    ImageHeader.Add("jpg", new byte[] { 255, 216, 255 });
    ImageHeader.Add("png", new byte[] { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 });
    FilesHeader.Add("pdf", new byte[] { 37, 80, 68, 70, 45, 49, 46, 53 });
    FilesHeader.Add("docx", new object[] { new byte[] { 80, 75, 3, 4, 20, 0, 6, 0, 8, 0, 0, 0, 33 }, new Regex(@"word/_rels/document\.xml\.rels", RegexOptions.IgnoreCase) });
    FilesHeader.Add("xlsx", new object[] { new byte[] { 80, 75, 3, 4, 20, 0, 6, 0, 8, 0, 0, 0, 33 }, new Regex(@"xl/_rels/workbook\.xml\.rels", RegexOptions.IgnoreCase) });
    FilesHeader.Add("pptx", new object[] { new byte[] { 80, 75, 3, 4, 20, 0, 6, 0, 8, 0, 0, 0, 33 }, new Regex(@"ppt/_rels/presentation\.xml\.rels", RegexOptions.IgnoreCase) });
    FilesHeader.Add("doc", new object[] { new byte[] { 208, 207, 17, 224, 161, 177, 26, 225 }, new Regex(@"microsoft( office)? word(?![\s\S]*?microsoft)", RegexOptions.IgnoreCase) });
    FilesHeader.Add("xls", new object[] { new byte[] { 208, 207, 17, 224, 161, 177, 26, 225 }, new Regex(@"microsoft( office)? excel(?![\s\S]*?microsoft)", RegexOptions.IgnoreCase) });
    FilesHeader.Add("ppt", new object[] { new byte[] { 208, 207, 17, 224, 161, 177, 26, 225 }, new Regex(@"c.u.r.r.e.n.t. .u.s.e.r(?![\s\S]*?[a-z])", RegexOptions.IgnoreCase) });
    FilesHeader.Add("avi", new byte[] { 65, 86, 73, 32 });
    FilesHeader.Add("mpg", new byte[] { 0, 0, 1, 0xBA });
    FilesHeader.Add("mpeg", new byte[] { 0, 0, 1, 0xB3 });
    FilesHeader.Add("rar", new byte[] { 82, 97, 114, 33, 26, 7 });
    FilesHeader.Add("zip", new byte[] { 80, 75, 3, 4 });
  }

  private static string DateTimeStamp()
  {
    return DateTime.Now.ToString("yyyyMMddHHmmss") + ra.Next(0, 99999).ToString("00000");
  }

  private static string FileType(Stream str)
  {
    string FileExt = string.Empty;
    foreach (string ext in FilesHeader.Keys)
    {
      byte[] header = FilesHeader[ext].GetType() == (new byte[] { }).GetType() ? (byte[])FilesHeader[ext] : (byte[])(((object[])FilesHeader[ext])[0]);
      byte[] test = new byte[header.Length];
      str.Position = 0;
      str.Read(test, 0, test.Length);
      bool same = true;
      for (int i = 0; i < test.Length; i++)
      {
        if (test[i] != header[i])
        {
          same = false;
          break;
        }
      }
      if (FilesHeader[ext].GetType() != (new byte[] { }).GetType() && same)
      {
        object[] obj = (object[])FilesHeader[ext];
        bool exists = false;
        if (obj[1].GetType().ToString() == "System.Int32")
        {
          for (int ii = 2; ii < obj.Length; ii++)
          {
            if (str.Length >= (int)obj[1])
            {
              str.Position = str.Length - (int)obj[1];
              byte[] more = (byte[])obj[ii];
              byte[] testmore = new byte[more.Length];
              str.Read(testmore, 0, testmore.Length);
              if (Encoding.GetEncoding(936).GetString(more) == Encoding.GetEncoding(936).GetString(testmore))
              {
                exists = true;
                break;
              }
            }
          }
        }
        else if (obj[1].GetType().ToString() == "System.Text.RegularExpressions.Regex")
        {
          Regex re = (Regex)obj[1];
          str.Position = 0;
          byte[] buffer = new byte[(int)str.Length];
          str.Read(buffer, 0, buffer.Length);
          string txt = Encoding.ASCII.GetString(buffer);
          if (re.IsMatch(txt))
          {
            exists = true;
          }
        }
        if (!exists)
        {
          same = false;
        }
      }
      if (same)
      {
        FileExt = ext;
        break;
      }
    }
    return FileExt;
  }

  private static string ImageType(Stream str)
  {
    string FileExt = string.Empty;
    foreach (string ext in ImageHeader.Keys)
    {
      byte[] header = ImageHeader[ext];
      byte[] test = new byte[header.Length];
      str.Position = 0;
      str.Read(test, 0, test.Length);
      bool same = true;
      for (int i = 0; i < test.Length; i++)
      {
        if (test[i] != header[i])
        {
          same = false;
          break;
        }
      }
      if (same)
      {
        FileExt = ext;
        break;
      }
    }
    if (!string.IsNullOrEmpty(FileExt))
    {
      Encoding[] chkList = new Encoding[] { Encoding.ASCII, Encoding.UTF8, Encoding.GetEncoding(936) };
      for (int i = 0; i < chkList.Length; i++)
      {
        str.Position = 0;
        string str_test = new StreamReader(str, chkList[i]).ReadToEnd();
        if (Regex.IsMatch(str_test, @"^[^\u0000-\u0008\u000B-\u000C\u000E-\u001F]*$"))
        {
          FileExt = string.Empty;
          break;
        }
      }
    }
    return FileExt;
  }

  private static void CreateFolder(string path)
  {
    string t_path = HttpContext.Current.Server.MapPath(path);
    if (!Directory.Exists(t_path))
    {
      Directory.CreateDirectory(t_path);
    }
  }

  private static string CreateFileName(string name, string ext)
  {
    string filename = "/Upload/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + ext + "/" + (autonamed ? DateTimeStamp() + "." + ext : name);
    if (File.Exists(HttpContext.Current.Server.MapPath(filename)))
    {
      return CreateFileName(name, ext);
    }
    else
    {
      return filename;
    }
  }

  private static string SaveAs(HttpPostedFile file, string Ext)
  {
    string filename = CreateFileName(file.FileName, Ext);
    CreateFolder(Regex.Match(filename, @"^[\s\S]*?(?=[^\\/]+$)").Value);
    file.SaveAs(HttpContext.Current.Server.MapPath(filename));
    return Regex.Match(HttpContext.Current.Request.Url.ToString(), @"^[\s\S]*?(?=(?<!/)/(?!/))").Value + filename;
  }

  private static void SaveInvalid(HttpPostedFile file)
  {
  }
  // 每次提交之前調(diào)用此方法,確認(rèn)返回內(nèi)容正確
  public static void Clear()
  {
    script = string.Empty;
  }

  public static void Save(HttpPostedFile file)
  {
    if (file.ContentLength == 0)
    {
      if (file.FileName.Length > 0)
      {
        script += (script.Length > 0 ? "," : "") + "{filename:'" + file.FileName + "',upload:false,length:0,target:null,type:''}";
      }
    }
    else
    {
      if (Regex.IsMatch(file.ContentType, @"^image/"))
      {
        string ext = ImageType(file.InputStream);
        if (string.IsNullOrEmpty(ext))
        {
          SaveInvalid(file);
          script += (script.Length > 0 ? "," : "") + "{filename:'" + file.FileName + "',upload:false,length:" + file.ContentLength + ",target:null,type:''}";
        }
        else
        {
          string filename = SaveAs(file, ext);
          script += (script.Length > 0 ? "," : "") + "{filename:'" + file.FileName + "',upload:true,length:" + file.ContentLength + ",target:'" + filename + "',type:'" + ext + "'}";
        }
      }
      else if (Regex.IsMatch(file.ContentType, @"^text/"))
      {
      }
      else
      {
        string ext = FileType(file.InputStream);
        if (string.IsNullOrEmpty(ext))
        {
          SaveInvalid(file);
          script += (script.Length > 0 ? "," : "") + "{filename:'" + file.FileName + "',upload:false,length:" + file.ContentLength + ",target:null,type:'',header:[" + "" + "]}";
        }
        else
        {
          string filename = SaveAs(file, ext);
          script += (script.Length > 0 ? "," : "") + "{filename:'" + file.FileName + "',upload:true,length:" + file.ContentLength + ",target:'" + filename + "',type:'" + ext + "'}";
        }
      }
    }
  }
}

調(diào)用頁面:

using System;
using System.Web;

public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    HttpFileCollection files = Request.Files;
    FileUpload.Clear();
    for (int i = 0; i < files.Count; i++)
    {
      FileUpload.Save(files[i]);
    }
    Response.Write(FileUpload.Script);
  }
}

功能至此完成,讀者還可以根據(jù)自身需要進(jìn)一步作出修改與完善。

相關(guān)文章

  • C#中使用WinRAR實(shí)現(xiàn)加密壓縮及解壓縮文件

    C#中使用WinRAR實(shí)現(xiàn)加密壓縮及解壓縮文件

    這篇文章主要介紹了C#中使用WinRAR實(shí)現(xiàn)加密壓縮及解壓縮文件,本文直接給出實(shí)例代碼,代碼中包含詳細(xì)注釋,需要的朋友可以參考下
    2015-07-07
  • Unity?UGUI的PointerEventData的介紹及使用

    Unity?UGUI的PointerEventData的介紹及使用

    這篇文章主要為大家介紹了Unity?UGUI的PointerEventData的介紹及使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-07-07
  • 淺談C# 9.0 新特性之只讀屬性和記錄

    淺談C# 9.0 新特性之只讀屬性和記錄

    這篇文章主要介紹了C# 9.0 新特性之只讀屬性和記錄的的相關(guān)資料,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以參考下
    2020-06-06
  • c# TreeView添加右鍵快鍵菜單有兩種方法

    c# TreeView添加右鍵快鍵菜單有兩種方法

    c# TreeView添加右鍵快鍵菜單有兩種方法,需要的朋友可以參考一下
    2013-04-04
  • C#定時(shí)每天00點(diǎn)00分00秒自動重啟軟件

    C#定時(shí)每天00點(diǎn)00分00秒自動重啟軟件

    這篇文章主要為大家詳細(xì)介紹了C#定時(shí)每天00點(diǎn)00分00秒自動重啟軟件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-08-08
  • WinForm限制窗體不能移到屏幕外的方法

    WinForm限制窗體不能移到屏幕外的方法

    這篇文章主要介紹了WinForm限制窗體不能移到屏幕外的方法,實(shí)例分析了C#中WinForm窗體操作的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-08-08
  • C#事件處理和委托event delegate實(shí)例簡述

    C#事件處理和委托event delegate實(shí)例簡述

    這篇文章主要介紹了C#事件處理和委托event delegate的簡單實(shí)例,較為詳細(xì)的講述了C#事件處理和委托的聲明與實(shí)現(xiàn)過程,代碼簡單易懂,需要的朋友可以參考下
    2014-09-09
  • C#實(shí)現(xiàn)視頻的批量剪輯功能

    C#實(shí)現(xiàn)視頻的批量剪輯功能

    這篇文章主要介紹了C#實(shí)現(xiàn)視頻的批量剪輯功能,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-03-03
  • C#設(shè)置右鍵菜單的方法

    C#設(shè)置右鍵菜單的方法

    這篇文章主要介紹了C#設(shè)置右鍵菜單的方法,實(shí)例分析了C#設(shè)置右鍵菜單的相關(guān)技巧,需要的朋友可以參考下
    2015-06-06
  • WPF使用DrawingContext實(shí)現(xiàn)繪制刻度條

    WPF使用DrawingContext實(shí)現(xiàn)繪制刻度條

    這篇文章主要為大家詳細(xì)介紹了如何利用WPF DrawingContext實(shí)現(xiàn)繪制刻度條,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)或工作有一定幫助,感興趣的小伙伴可以了解一下
    2022-09-09

最新評論

彩票| 商都县| 彰武县| 简阳市| 大厂| 乐山市| 怀来县| 阳西县| 基隆市| 寿光市| 布拖县| 禹州市| 区。| 哈巴河县| 清水县| 治多县| 嫩江县| 张家川| 墨江| 托里县| 衡阳市| 高尔夫| 开江县| 丹江口市| 库尔勒市| 苏尼特左旗| 柳林县| 象山县| 清水县| 手机| 东乡| 吉木乃县| 庄河市| 玉环县| 板桥市| 井陉县| 昌邑市| 长乐市| 四会市| 望谟县| 镇雄县|