C#检测上传文件的真实格式真实类型

30 篇文章 1 订阅

调用验证

ASP.NET Core 5

//.NET5   
//ASP.NET Core 5上传文件
public async Task<ActionResult> UploadImg(IFormFile file)
{
	//检查文件真实格式
	System.IO.MemoryStream ms = new System.IO.MemoryStream();
	await file.CopyToAsync(ms);
	byte[] bytes = new byte[160];
	ms.Position = 0;
	await ms.ReadAsync(bytes, 0, bytes.Length);
	bool pass = FileTypeCheck.IsValidFileExtension(file.FileName, bytes);
	if (!pass)
	{
		return Json(new Result("文件格式不正确,允许的上传格式为" + allow_img_type));
	}
	  object imgInfo = new
		{
			//图片保存文件名
			fileName = objectName,
			//存储桶
			bucket = bucketName
		};
	 return Json(imgInfo);
}



检测文件真实格式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebNetCore5_Img_Storage.Model.Tool
{
    /// <summary>
    /// 文件真实格式检查
    /// </summary>
    public class FileTypeCheck
    {
        private readonly static Dictionary<string, List<byte[]>> fileSignature = new Dictionary<string, List<byte[]>>
                    {
                    { ".DOC", new List<byte[]> { new byte[] { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 } } },
                    { ".DOCX", new List<byte[]> { new byte[] { 0x50, 0x4B, 0x03, 0x04 } } },
                    { ".PDF", new List<byte[]> { new byte[] { 0x25, 0x50, 0x44, 0x46 } } },
                    { ".ZIP", new List<byte[]>
                                            {
                                              new byte[] { 0x50, 0x4B, 0x03, 0x04 },
                                              new byte[] { 0x50, 0x4B, 0x4C, 0x49, 0x54, 0x55 },
                                              new byte[] { 0x50, 0x4B, 0x53, 0x70, 0x58 },
                                              new byte[] { 0x50, 0x4B, 0x05, 0x06 },
                                              new byte[] { 0x50, 0x4B, 0x07, 0x08 },
                                              new byte[] { 0x57, 0x69, 0x6E, 0x5A, 0x69, 0x70 }
                                                }
                                            },

                    //图片格式
                    { ".PNG", new List<byte[]> { new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A } } },
                    { ".JPG", new List<byte[]>
                                    {
                                              new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 },
                                              new byte[] { 0xFF, 0xD8, 0xFF, 0xE1 },
                                              new byte[] { 0xFF, 0xD8, 0xFF, 0xE8 }
                                    }
                                    },
                    { ".JPEG", new List<byte[]>
                                        {
                                            new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 },
                                            new byte[] { 0xFF, 0xD8, 0xFF, 0xE2 },
                                            new byte[] { 0xFF, 0xD8, 0xFF, 0xE3 }
                                        }
                                        },
                     { ".GIF", new List<byte[]> { new byte[] { 0x47, 0x49, 0x46, 0x38 } } },
                     { ".BMP", new List<byte[]> { new byte[] { 0x42, 0x4D } } },
                     { ".JFIF", new List<byte[]> { new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46 } } },


                     //视频格式
                     //高清,高占用空间
                    { ".MP4", new List<byte[]> {
                                            new byte[] { 0x00,0x00,0x00,0x18,0x66,0x74,0x79,0x70,0x6D,0x70,0x34,0x32 },
                                            new byte[] { 0x00,0x00,0x00,0x1C,0x66,0x74,0x79,0x70,0x6D,0x70,0x34,0x32 },
                                            new byte[] { 0x00,0x00,0x00,0x20,0x66,0x74,0x79,0x70,0x69,0x73,0x6F, 0x6D },
                                        }
                                        },
                     //高清,中度占用空间
                    { ".MKV", new List<byte[]> {
                                                new byte[] { 0x1A, 0x45, 0xDF, 0xA3, 0xA3, 0x42, 0x86, 0x81, 0x01, 0x42, 0xF7  }
                                            }
                                            },
                    //高清,中度占用空间
                    { ".MOV", new List<byte[]> {
                                                new byte[] { 0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74 }
                                            }
                                            },
                     //高清,低占用空间
                    { ".M4V", new List<byte[]> {
                                                new byte[] { 0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x56 }
                                            }
                                            },
                    //高清,低占用空间
                    { ".WEBM", new List<byte[]> {
                                                new byte[] { 0x1A, 0x45, 0xDF, 0xA3, 0x9F, 0x42, 0x86, 0x81, 0x01, 0x42, 0xF7, 0x81, 0x01, 0x42, 0xF2 }
                                            }
                                            },
                      //低质量
                     { ".WMV", new List<byte[]> {
                                                  new byte[] { 0x30,0x26,0xB2,0x75,0x8E,0x66,0xCF,0x11}                          
                                            }
                                            },
                        //低质量
                       { ".AVI", new List<byte[]> {
                                              new byte[] { 0x52, 0x49, 0x46, 0x46, 0x84, 0x4A, 0x1E, 0x00, 0x41, 0x56, 0x49 }
                                            }
                                            },
                         //低质量
                       { ".FLV", new List<byte[]> {
                                              new byte[] { 0x46, 0x4C, 0x56 }
                                            }
                                            },


                    //电子表格
                    { ".XLS", new List<byte[]>
                                            {
                                              new byte[] { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 },
                                              new byte[] { 0x09, 0x08, 0x10, 0x00, 0x00, 0x06, 0x05, 0x00 },
                                              new byte[] { 0xFD, 0xFF, 0xFF, 0xFF }
                                            }
                                            },
                    { ".XLSX", new List<byte[]> { new byte[] { 0x50, 0x4B, 0x03, 0x04 } } },
                };

        /// <summary>
        /// 文件真实格式检查
        /// </summary>
        /// <param name="fileName">文件名,包含后缀</param>
        /// <param name="fileData">文件头字节数组,请传200个以内</param>
        /// <param name="allowedChars">允许的例外字节数组</param>
        /// <returns></returns>
        public static bool IsValidFileExtension(string fileName, byte[] fileData, byte[] allowedChars = null)
        {
            if (string.IsNullOrEmpty(fileName) || fileData == null || fileData.Length == 0)
            {
                return false;
            }
            bool flag = false;
            string ext = System.IO.Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(ext))
            {
                return false;
            }
            ext = ext.ToUpperInvariant();

            //if (ext.Equals(".TXT") || ext.Equals(".CSV") || ext.Equals(".PRN"))
            //{
            //    foreach (byte b in fileData)
            //    {
            //        if (b > 0x7F)
            //        {
            //            if (allowedChars != null)
            //            {
            //                if (!allowedChars.Contains(b))
            //                {
            //                    return false;
            //                }
            //            }
            //            else
            //            {
            //                return false;
            //            }
            //        }
            //    }
            //    return true;
            //}

            if (!fileSignature.ContainsKey(ext))
            {
                return true;
            }
            List<byte[]> sig = fileSignature[ext];
            foreach (byte[] b in sig)
            {
                var curFileSig = new byte[b.Length];
                Array.Copy(fileData, curFileSig, b.Length);
                if (curFileSig.SequenceEqual(b))
                {
                    //验证格式通过
                    flag = true;
                    break;
                }
            }
            return flag;
        }

    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王焜棟琦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值