• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >C#教程 > .net文件上传时实现通过文件头确认文件类型的方法

.net文件上传时实现通过文件头确认文件类型的方法

作者: 字体:[增加 减小] 来源:互联网 时间:2017-05-28

通过本文主要向大家介绍了net4.0安装时严重错误,net4.0安装时回滚,cad安装时缺少net,安装cad时缺少net组件,net4.5安装时回滚等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

本文实例讲述了.net文件上传时实现通过文件头确认文件类型的方法,其中 script 用来返回给页面的数据,读者还可以根据自身需要对相关部分自行修改。另外,文件头也可以自行添加定义。

主要代码如下:

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)
  {
  }
  // 每次提交之前调用此方法,确认返回内容正确
  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



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • .net文件上传时实现通过文件头确认文件类型的方法

相关文章

  • 2017-05-28winform C#获得Mac地址,IP地址,子网掩码,默认网关的实例
  • 2017-05-28C# 如何获取出错的错误所在行数信息 原创
  • 2017-05-28WinForm的延时加载控件概述
  • 2017-05-28C#实现txt定位指定行完整实例
  • 2017-05-28C#引用类型和值类型的介绍与实例
  • 2017-05-28C#针对xml基本操作及保存配置文件应用实例
  • 2017-05-28C#中dotnetcharting的用法实例详解
  • 2017-05-28c#简单读取文本的实例方法
  • 2017-05-28C#中DropDownList动态生成的方法
  • 2017-05-28C#中WebBrowser.DocumentCompleted事件多次调用问题解决方法

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • C#实现的简单链表类实例
    • C#编程自学之数据类型和变量一
    • 微信服务号推送模板消息接口
    • C#实现把彩色图片灰度化代码分享
    • C#程序优化-有效减少CPU占用率
    • C# 字符串string和内存流MemoryStream及比特数组byte[]之间相互转换
    • 深入分析NTFS中文件被锁定导致Process.Start失败的详解
    • C#特性 匿名类型与隐式类型局部变量使用介绍
    • Windows系统中使用C#读取文本文件内容的小示例
    • C#简单实现文件上传功能

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有