| 圖片中帶木馬怎麼辦? 我們在服務端加上一層防護 using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; using System.Text; /// <summary> /// UpLoadFile 的摘要說明 /// </summary> public class UpLoadFile:System.Web.UI.Page { public UpLoadFile() { // // TODO: 在此處添加建構函式邏輯 // } /// <summary> /// 檔案上傳 /// </summary> /// <param name="UpFile">上傳控制項</param> /// <param name="SourceImg">源圖片名子</param> /// <param name="SourcePage">那個頁面的操作</param> /// <returns>返回上傳的檔案名稱,可以為空白</returns> public static string UpLoadFileImg(HttpPostedFile UpFile, string SourceImg, System.Web.UI.Page SourcePage) { //鎖定頁面 SourcePage.Application.Lock(); string Img = UpFile.FileName.Trim();//擷取檔案名稱 string WebPath = SourcePage.Server.MapPath("UpLoadFile/UsersPhoto/");//上傳到指定路徑 string Exten = Path.GetExtension(UpFile.FileName).ToUpper();//擷取檔案的副檔名 int FileLength = UpFile.ContentLength;//檔案大小 string FileType = UpFile.ContentType.ToUpper();//擷取檔案的類型 if (Img != "") { //上傳檔案第一級副檔名和類型驗證 if (Exten != ".GIF" && Exten != ".JPG" && FileType != "" && FileType != "") { Img = "No"; WebScript.JavaScript.OnlyAlertMsg(SourcePage, "上傳檔案格式只能是(.jpg||.gif)格式!"); } else if (FileLength / 1024 / 1024 > 1) //上傳檔案不能大於1M { Img = "No"; WebScript.JavaScript.OnlyAlertMsg(SourcePage, "上傳圖片不能超過1M"); } else { Img = DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("-", "") + Exten;//以目前時間來命名 //上傳檔案 UpFile.SaveAs(WebPath + Img); //最後一部進階驗證,圖片上傳後的操作,判斷是否真的是圖片 StreamReader sr = new StreamReader(WebPath + Img, Encoding.Default); string strContent = sr.ReadToEnd(); sr.Close(); string str = "request|script|.getfolder|.createfolder|.deletefolder|.createdirectory|.deletedirectory|.saveas|wscript.shell|script.encode|server.|.createobject|execute|activexobject|language="; foreach (string s in str.Split('|')) if (strContent.IndexOf(s) != -1) { File.Delete(WebPath + Img); Img = "No"; WebScript.JavaScript.OnlyAlertMsg(SourcePage, "這張圖片格式非法,請換一張,謝謝!"); break; } //刪除源檔案 if (Img != "No" && File.Exists(WebPath + SourceImg)) File.Delete(WebPath + SourceImg);//如果檔案已經存在就刪除 } } else Img = SourceImg; //取消鎖定頁面 SourcePage.Application.UnLock(); return Img; |