we have checked the posted file of the FileUpload and pass it to the IsImageFile() method that returns a Boolean type for checking the actual type of the posted file. If the file contains image extension such as “jpg”, “gif”, “bmp” and “png” then it will return TRUE else it will return false.

  1. private void StartUpLoad() 
  2.     if (FileUpload1.HasFile) 
  3.     { 
  4.         HttpPostedFile postedFile = FileUpload1.PostedFile; 
  5.         if (IsImageFile(postedFile)) 
  6.         { 
  7.             //Save image here 
  8.         } 
  9.         else 
  10.         { 
  11.             Response.Write("Invalid File, Cannot Upload!"); 
  12.         } 
  13.     } 
  14.     else 
  15.     { 
  16.         Response.Write("Please select a File"); 
  17.     } 
  18.  
  19. protected bool IsImageFile(HttpPostedFile file) 
  20.     bool isImage = false
  21.     System.IO.FileStream fs = new System.IO.FileStream(file.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); 
  22.     System.IO.BinaryReader br = new System.IO.BinaryReader(fs); 
  23.  
  24.     string fileclass = ""
  25.     byte buffer; 
  26.     try 
  27.     { 
  28.         buffer = br.ReadByte(); 
  29.         fileclass = buffer.ToString(); 
  30.         buffer = br.ReadByte(); 
  31.         fileclass += buffer.ToString(); 
  32.     } 
  33.     catch 
  34.     { 
  35.         return false
  36.     } 
  37.     finally 
  38.     { 
  39.         br.Close(); 
  40.         fs.Close(); 
  41.     } 
  42.  
  43.     /*extension lists with codes 
  44.      *7173        gif 
  45.      *255216      jpg 
  46.      *13780       png 
  47.      *6677        bmp 
  48.      *239187      txt,aspx,asp,sql 
  49.      *208207      xls.doc.ppt 
  50.      *6063        xml 
  51.      *6033        htm,html 
  52.      *4742        js 
  53.      *8075        xlsx,zip,pptx,mmap,zip 
  54.      *8297        rar   
  55.      *01          accdb,mdb 
  56.      *7790        exe,dll           
  57.      *64101       bat 
  58.      */ 
  59.  
  60.     //only allow images    jpg       gif     bmp     png      
  61.     String[] fileType = { "255216""7173""6677""13780" }; 
  62.     for (int i = 0; i < fileType.Length; i++) 
  63.     { 
  64.         if (fileclass == fileType[i]) 
  65.         { 
  66.             isImage = true
  67.             break
  68.         } 
  69.     } 
  70.     return isImage; 

 

本日志由 flyinweb 于 2010-11-05 15:18:08 发表到 DotNet专栏 中,目前已经被浏览 4053 次,评论 0 次;

作者添加了以下标签: extension