ASP.NET在上傳文件時對文件類型的高級判斷的代碼
更新時間:2009年12月21日 03:48:51 作者:
在上傳文件過程中,可以通過修改擴展名來逃過文件類型的判斷并實現(xiàn)上傳,就需要可以驗證究竟是什么文件。下面的代碼大家可以測試下。
復(fù)制代碼 代碼如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void bt_upload_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.PostedFile.FileName == "")
{
this.lb_info.Text = "請選擇文件!";
}
else
{
string filepath = FileUpload1.PostedFile.FileName;
if (IsAllowedExtension(FileUpload1) == true)
{
string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
string serverpath = Server.MapPath("images/") + filename;
FileUpload1.PostedFile.SaveAs(serverpath);
this.lb_info.Text = "上傳成功!";
}
else
{
this.lb_info.Text = "請上傳圖片";
}
}
}
catch (Exception error)
{
this.lb_info.Text = "上傳發(fā)生錯誤!原因:" + error.ToString();
}
}
public static bool IsAllowedExtension(FileUpload hifile)
{
System.IO.FileStream fs = new System.IO.FileStream(hifile.PostedFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch
{
}
r.Close();
fs.Close();
if (fileclass == "255216" || fileclass == "7173")//說明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
{
return true;
}
else
{
return false;
}
}
}
測試通過....
您可能感興趣的文章:
相關(guān)文章
ASP.NET Core 2.0 本地文件操作問題及解決方案
這篇文章主要介紹了ASP.NET Core 2.0 本地文件操作問題及解決方案,需要的朋友可以參考下2017-10-10ASP.NET如何定時調(diào)用WebService服務(wù)
在ASP.NET程序中,可以通過Time組件實現(xiàn)定時器功能,但是它與數(shù)據(jù)庫中的任務(wù)計劃不一樣,它必須基于程序正在運行中才可生效,而數(shù)據(jù)庫任務(wù)計劃是不需要基于ASP.NET程序運行而執(zhí)行任務(wù)。2015-10-10ASP.NET Core使用HttpClient調(diào)用WebService
這篇文章介紹了ASP.NET Core使用HttpClient調(diào)用WebService的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03Entity Framework Core生成列并跟蹤列記錄
這篇文章介紹了Entity Framework Core生成列并跟蹤列記錄的方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-02-02Asp.net TreeView來構(gòu)建用戶選擇輸入的方法 推薦
選擇優(yōu)于輸入,這是一般人的共識,面對繁多的數(shù)據(jù),提供良好的選擇界面,一方面增強用戶的界面體驗,一方面也提高了數(shù)據(jù)的準確性,更節(jié)省了用戶的寶貴時間。2009-12-12ASP.NET+XML打造網(wǎng)絡(luò)硬盤原理分析
文件傳送常用的三種方式:FTP、Email及網(wǎng)上鄰居,都在一定程度上實現(xiàn)了文件數(shù)據(jù)的交流,但它們都主要面向“點對點”的傳送,無法實現(xiàn)一塊空間,資源互見的應(yīng)用需求,這種基于點對多的共享模式需要尋求另外的傳輸途徑,網(wǎng)絡(luò)硬盤就是一種很好的解決方式2012-09-09