ASP.NET通過byte正確安全的判斷上傳檔案格式_實用技巧

來源:互聯網
上載者:User

ASP.NET中在判斷檔案格式時,我們以前常用的方法就是通過截取副檔名來做判斷,或者通過ContentType (MIME) 判斷,這兩種方法都不太安全,因為這兩種方式使用者都可以偽造,從而達可以攻擊網站,實現給網站掛馬等目的。

下面介紹通過byte擷取檔案類型,來做判斷的方式

if (Request.Files.Count > 0){  //這裡只測試上傳第一張圖片file[0]  HttpPostedFile file0 = Request.Files[0];      //轉換成byte,讀取圖片MIME類型  Stream stream;  //int contentLength = file0.ContentLength; //檔案長度  byte[] fileByte = new byte[2];//contentLength,這裡我們唯讀取檔案長度的前兩位用於判斷就好了,這樣速度比較快,剩下的也用不到。  stream = file0.InputStream;  stream.Read(fileByte, 0, 2);//contentLength,還是取前兩位  stream.Close();      string fileFlag = "";  if (fileByte != null && fileByte.Length > 0)//圖片資料是否為空白  {    fileFlag = fileByte[0].ToString() + fileByte[1].ToString();           }  string[] fileTypeStr = { "255216", "7173", "6677", "13780" };//對應的圖片格式jpg,gif,bmp,png  if (fileTypeStr.Contains(fileFlag))  {    file0.SaveAs(Server.MapPath("~/" + file0.FileName));  }  else  {    Response.Write("圖片格式不正確:" + fileFlag);  }}

常見檔案類型對應的byte資料

199196 sqlite資料庫檔案
7076 flv視頻檔案
6787 swf視頻檔案
7173 gif
255216 jpg
13780 png
6677 bmp
239187 txt,aspx,asp,sql
208207 xls.doc.ppt
6063 xml
6033 htm,html
4742 js
8075 xlsx,zip,pptx,mmap,zip,docx
8297 rar
01 accdb,mdb
7790 exe,dll
5666 psd
255254 rdp
10056 bt種子
64101 bat
255254 csv
3780 pdf

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.