2012-03-23 59 views

回答

0

如果你想絕對確定,最好檢查HttpPostedFileBase的魔法字節流。這是因爲有些應用程序可能會將它寫爲您認爲可以處理的擴展名(例如MP4),但實際上它是另一種格式,如M4V。

例如,要檢查流是否爲MP4變體流,可以檢查流是否以字節0x00,0x00,0x00,0x20,0x66,0x74,0x79,0x70,0x6D,0x70和0x34開頭。你可以找到更多的格式here

像這樣的東西可能工作:

public static bool IsMP4(System.IO.Stream stream) 
{ 
    return HasMagicBytes(stream, 0, 0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34); 
} 

public static bool HasMagicBytes (System.IO.Stream stream, int offset, params byte[] magicBytes) 
{ 
    try { 
     bool match = false; 
     byte[] bytes = new byte[magicBytes.Length]; 
     if (stream.Read (bytes, offset, magicBytes.Length) == magicBytes.Length) { 
      for (int i = 0; i < magicBytes.Length; i++) { 
       if (bytes [i] != magicBytes [i]) { 
        return false; 
       } 
      } 
      return true; 
     } else { 
      return false; 
     } 

    } finally { 
     stream.Seek (0, System.IO.SeekOrigin.Begin); 
    } 

} 

一些應注意的流是否是可搜索。這種技術對於較大的文件相當有效。爲了使這種可重複使用的,你可以寫一個ValidationAttribute所以有可能這樣定義你的模型:

public class MyModel 
{ 
    [CheckFormat(0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34)] 
    public HttpPostedFileBase MyFile { get; set; } 
} 

但我會留給你進一步調查。