c# 圖片木馬防護

來源:互聯網
上載者:User
圖片中帶木馬怎麼辦?  我們在服務端加上一層防護

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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.