今天在作圖片註冊的功能的時候,測試提出一個問題:將隨便一個非圖片文件將後綴名改成jpg或其餘,上傳時應檢驗圖片合法性。而後同事給提供了根據文件流前兩個字節判斷文件真實格式的思路,代碼以下:ide
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。spa
可是此方法不能夠用於判斷視頻格式,不知走過路過的有木有較好的解決方案。code