C# 通用檔案上傳類

來源:互聯網
上載者:User

1、Upfile.aspx:
複製代碼 代碼如下:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Upfile.aspx.cs" Inherits="Inc_Upfile" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
<html xmlns="http://www.w3.org/1999/xhtml"; >
<head runat="server">
<title>上傳檔案</title>
<link href="../Manage/Style.Css" type="text/css" rel=Stylesheet />
</head>
<body>
<form id="form1" runat="server">
<div style="left: 0px; clip: rect(0px auto auto 0px); position: absolute; top: 0px">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上傳檔案" CssClass="btn2" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
</form>
</body>
</html>

Upfile.aspx.cs

代碼 複製代碼 代碼如下: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 Inc_Upfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Cut By 夢溪苑。
}
protected void Button1_Click(object sender, EventArgs e)
{
AllSheng.upload UpFiles = new AllSheng.upload();
//HttpPostedFile File = FileUpload1.PostedFile;
// AllSheng.UploadObj.PhotoSave("/", FileUpload1);
HttpFileCollection files = HttpContext.Current.Request.Files;
UpFiles.Path = "../UpLoadfiles";
String ReStr= UpFiles.SaveAs(files).ToString();
Label1.Text = ReStr;
UpFiles = null;
}
}

3、類檔案:

代碼 複製代碼 代碼如下:using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/**//// <summary>
/// Cls_Upfile 的摘要說明
/// </summary>
///
namespace AllSheng
{
public class upload
{
變數#region 變數
System.Web.HttpPostedFile postedFile;
protected string localFileName;//原檔案名稱(含副檔名)
protected string localFileExtension;//原副檔名
protected long localFileLength;//原檔案大小
protected string localFilePath;//原檔案路徑
protected string saveFileName;//儲存的檔案名稱(含副檔名)
protected string saveFileExtension;//儲存的副檔名
//protected long saveFileLength;//儲存的檔案大小
protected string saveFilePath;//儲存檔案的伺服器端的完整路徑
protected string saveFileFolderPath;//儲存檔案的伺服器端的檔案夾路徑
private string path = null;
private string fileType = null;
private int sizes = 0;
#endregion
upload():初始設定變數#region upload():初始設定變數
/**//// <summary>
/// 初始設定變數
/// </summary>
public upload()
{
path = @"uploadimages"; //上傳路徑
fileType = "jpg|gif|bmp|jpeg|png|rar|doc";
sizes = 200; //傳檔案的大小,預設200KB
}
#endregion
設定傳入的值:Path/Sizes/FileType#region 設定傳入的值:Path/Sizes/FileType
/**//// <summary>
/// 設定上傳路徑,如:uploadimages
/// </summary>
public string Path
{
set
{
path = @"" + value + @"";
}
}
/**//// <summary>
/// 設定上傳檔案大小,單位為KB
/// </summary>
public int Sizes
{
set
{
sizes = value;
}
}
/**//// <summary>
/// 設定上傳檔案的類型,如:jpg|gif|bmp
/// </summary>
public string FileType
{
set
{
fileType = value;
}
}
#endregion
SaveAs()上傳檔案#region SaveAs()上傳檔案
public string SaveAs(System.Web.HttpFileCollection files)
{
string myReturn = "";
try
{
for (int iFile = 0; iFile < files.Count; iFile++)
{
postedFile = files[iFile];
//獲得檔案的上傳的路徑
localFilePath = postedFile.FileName;
//判斷上傳檔案路徑是否為空白
if (localFilePath == null || localFilePath == "")
{
//message("您沒有上傳資料呀,是不是搞錯了呀!");
//break;
continue;
}
else
{
判斷檔案大小#region 判斷檔案大小
//獲得上傳檔案的大小
localFileLength = postedFile.ContentLength;
//判斷上傳檔案大小
if (localFileLength >= sizes * 1024)
{
message("上傳的圖片不能大於" + sizes + "KB");
break;
}
#endregion
檔案夾#region 檔案夾
//擷取儲存檔案夾路徑
saveFileFolderPath = getSaveFileFolderPath(path);
#endregion
檔案名稱#region 檔案名稱
//獲得原檔案名稱(含副檔名)
localFileName = System.IO.Path.GetFileName(postedFile.FileName);
saveFileName = DateTime.UtcNow.ToString("yyyy" + "MM" + "dd" + "HH" + "mm" + "ss" + "ffffff");//"yyyy"+"MM"+"dd"+"HH"+"mm"+"ss"+"ffffff"
#endregion
副檔名#region 副檔名
//擷取原副檔名
localFileExtension = getFileExtension(localFileName);
//如果為真允許上傳,為假則不允許上傳
if (localFileExtension == "")
{
message("目前本系統支援的格式為:" + fileType);
}
//得到儲存檔案的副檔名,可根據需要更改副檔名
saveFileExtension = localFileExtension;
#endregion
//得到儲存檔案的完整路徑
saveFilePath = saveFileFolderPath + saveFileName + saveFileExtension;
postedFile.SaveAs(saveFilePath);
myReturn = myReturn + ((myReturn == "" || myReturn == null) ? "" : "|") + path.TrimStart(new char[] { '' }) + saveFileName + saveFileExtension;
//以下對文章的內容進行一些加工
System.Web.HttpContext.Current.Response.Write("<script>parent.Article_Content___Frame.FCK.EditorDocument.body.innerHTML+='<img src=" + saveFileName + saveFileExtension + " "+" border=0 />'</SCRIPT>");
}
}
}
catch
{
//異常
message("出現未知錯誤!");
myReturn = null;
}
return myReturn;
}
#endregion
getSaveFileFolderPath( ):獲得儲存的檔案夾的實體路徑#region getSaveFileFolderPath( ):獲得儲存的檔案夾的實體路徑
/**//// <summary>
/// 獲得儲存的檔案夾的實體路徑
/// 返回儲存的檔案夾的實體路徑,若為null則表示出錯
/// </summary>
/// <param name="format">儲存的檔案夾路徑 或者 格式化方式建立儲存檔案的檔案夾,如按日期"yyyy"+"MM"+"dd":20060511</param>
/// <returns>儲存的檔案夾的實體路徑,若為null則表示出錯</returns>
private string getSaveFileFolderPath(string format)
{
string mySaveFolder = null;
try
{
string folderPath = null;
//以目前時間建立檔案夾,
//!!!!!!!!!!!!以後用Regex替換下面的驗證語句!!!!!!!!!!!!!!!!!!!
if (format.IndexOf("yyyy") > -1 || format.IndexOf("MM") > -1 || format.IndexOf("dd") > -1 || format.IndexOf("hh") > -1 || format.IndexOf("mm") > -1 || format.IndexOf("ss") > -1 || format.IndexOf("ff") > -1)
{
//以通用標準時間建立檔案夾的名字
folderPath = DateTime.UtcNow.ToString(format);
mySaveFolder = System.Web.HttpContext.Current.Server.MapPath(".") + @"" + folderPath + @"";
}
else
{
mySaveFolder = System.Web.HttpContext.Current.Server.MapPath(".") + format;
}
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(mySaveFolder);
//判斷檔案夾否存在,不存在則建立
if (!dir.Exists)
{
dir.Create();
}
}
catch
{
message("擷取儲存路徑出錯");
}
return mySaveFolder;
}
#endregion
getFileExtension( ):擷取原檔案的副檔名#region getFileExtension( ):擷取原檔案的副檔名
/**//// <summary>
/// 擷取原檔案的副檔名,返回原檔案的副檔名(localFileExtension),該函數用到外部變數fileType,即允許的副檔名.
/// </summary>
/// <param name="myFileName">原檔案名稱</param>
/// <returns>原檔案的副檔名(localFileExtension);若返回為null,表明檔案無尾碼名;若返回為"",則表明副檔名為非法.</returns>
private string getFileExtension(string myFileName)
{
string myFileExtension = null;
//獲得副檔名
myFileExtension = System.IO.Path.GetExtension(myFileName);//若為null,表明檔案無尾碼名;
//分解允許上傳檔案的格式
if (myFileExtension != "")
{myFileExtension = myFileExtension.ToLower();//轉化為小寫
}
string[] temp = fileType.Split('|');
//設定上傳的檔案是否是允許的格式
bool flag = false;
//判斷上傳的檔案是否是允許的格式
foreach (string data in temp)
{
if (("." + data) == myFileExtension)
{
flag = true;
break;
}
}
if (!flag)
{
myFileExtension = "";//不能設定成null,因為null表明檔案無尾碼名;
}
return myFileExtension;
}
#endregion
message( ):彈出訊息框#region message( ):彈出訊息框
/**//// <summary>
/// 彈出訊息框,顯示內容(msg),點擊"確定"後頁面跳轉到該路徑(url)
/// </summary>
/// <param name="msg">顯示內容</param>
/// <param name="url">跳轉路徑</param>
private void message(string msg, string url)
{
System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('" + msg + "');window.location='" + url + "'</script>");
}
/**//// <summary>
/// 彈出訊息框,顯示內容(msg),無跳轉
/// </summary>
/// <param name="msg">顯示內容</param>
private void message(string msg)
{
System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('" + msg + "');</script>");
}
#endregion
}
}

相關文章

聯繫我們

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