今天在做图片注册的功能的时候,测试提出一个问题:将随便一个非图片文件将后缀名改为jpg或其他,上传时应检验图片合法性。然后同事给提供了根据文件流前两个字节判断文件真实格式的思路,代码如下:
public static FileExtension CheckFileType(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); System.IO.BinaryReader br = new System.IO.BinaryReader(fs); string fileType = string.Empty; ; try { byte data = br.ReadByte(); fileType += data.ToString(); data = br.ReadByte(); fileType += data.ToString(); FileExtension extension; try { extension = (FileExtension)Enum.Parse(typeof(FileExtension), fileType); } catch { extension = FileExtension.VALIDFILE; } return extension; } catch (Exception ex) { throw ex; } finally { if (fs != null) { fs.Close(); br.Close(); } } }
然后从网上找了各种文件所对应的字节关系如下:
public enum FileExtension { JPG = 255216, GIF = 7173, BMP = 6677, PNG = 13780, COM = 7790, EXE = 7790, DLL = 7790, RAR = 8297, ZIP = 8075, XML = 6063, HTML = 6033, ASPX = 239187, CS = 117115, JS = 119105, TXT = 210187, SQL = 255254, BAT = 64101, BTSEED = 10056, RDP = 255254, PSD = 5666, PDF = 3780, CHM = 7384, LOG = 70105, REG = 8269, HLP = 6395, DOC = 208207, XLS = 208207, DOCX = 208207, XLSX = 208207, VALIDFILE = 9999999 }
进行测试了一下,图片格式都OK。
但是此方法不可以用于判断视频格式,不知走过路过的有木有较好的解决方案。