.net文件上传时实现通过文件头确认文件类型的方法
作者:shichen2014 发布时间:2021-08-01 09:05:32
标签:.net,文件上传,文件类型
本文实例讲述了.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:'" + 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 + "'}";
}
}
}
}
}
调用页面:
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);
}
}
功能至此完成,读者还可以根据自身需要进一步作出修改与完善。


猜你喜欢
- 最近参与了开发一款旅行APP,其中包含实时聊天和动态评论功能,终于耗时几个月几个伙伴完成了,今天就小结一下至于实时聊天功能如果用户不多的情况
- 1,背景在开发中总会遇到一个可拖拽的悬浮View,不管是在开发中,还是在线上,都时长有这样的控件,我们通常遇到这种情况,经常需要自己封装,需
- 本文实例为大家分享了java查找图中两点之间所有路径的具体代码,基于邻接表,供大家参考,具体内容如下图类:package graph1;im
- Junit中的基本注解:@Test:使用该注解标注的public void方法会表示为一个测试方法;@BeforeClass:表示在类中的任
- 本文实例讲述了C#实现在启动目录创建快捷方式的方法。分享给大家供大家参考。具体如下:添加引用,选择 COM 选项卡并选择 Windows S
- 基础环境SpringBoot、Maven代码实现1.添加依赖<!--二维码生成 --><dependency&
- C#调用MFC 窗口 DLLMFC DLL创建一个窗口类,加public和AFX_EXT_CLASSMFC DLL属性注意MFC的使用:在共
- 这篇文章主要介绍了Java利用读写的方式实现音频播放代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需
- 本文实例为大家分享了Viewpager2实现登录注册引导页面的具体代码,供大家参考,具体内容如下介绍屏幕滑动是两个完整屏幕之间的切换,在设置
- 在Java中对集合进行操作时,有时候需要对类中的equals() 和 hashCode()进行方法重写.IDEA中实现了利用快捷键即可对上述
- Monkeyrunner 常用按键 &nbs
- 本文实例为大家分享了Android ViewPager实现轮播图效果的具体代码,供大家参考,具体内容如下先上一张效果图:说到ViewPage
- typora-copy-images-to: ./一键清除maven仓库中下载失败的jar包maven是一款非常优秀的项目管理工具,特别是其
- 1:在很多APP里点击返回键,都可以看到返回键由亮变为暗2:实现方法也是很简单的(1)新建一个页面<RelativeLayout &n
- 一、概念 工厂方法模式是类的创建模式,又叫虚
- OleDbConnection,OracleConnection 或者SqlConnection这种连接,直接执行sql语句。现在的连接方式
- 项目背景我们开发过程中会碰到这样一类问题,就是数据层或三方接口返回的Bean对象需要转换重新装换一下我们需要的对象。我们通常的做法就是通过g
- 第1部分 ArrayList介绍ArrayList简介ArrayList 是一个数组队列,相当于 动态数组。与Java中的数组相比,它的容量
- 目录1 HttpClient简介2 代码实现2.1 服务端2.1.1 新建控制器2.1.2 新建启动器2.2 客户端2.2.1 添加依赖2.
- 首先在layout布局中设置按钮和一个ImageView<Button android:id="@+id/sel