using System;
namespace UpFile
{
/// <summary>
/// upfile 的摘要說明。
/// </summary>
public class upfile
{
private string path = null;
private string fileType = null;
private int sizes = 0;
/// <summary>
/// 初始設定變數
/// </summary>
public upfile()
{
path = @"\uploadimages\"; //上傳路徑
fileType = "jpg|gif|bmp";
sizes = 200; //傳檔案的大小,預設200KB
}
/// <summary>
/// 設定上傳路徑,如:uploadimages\
/// </summary>
public string Path
{
set
{
path = @"\" + value + @"\";
}
}
/// <summary>
/// 設定上傳檔案大小,單位為KB
/// </summary>
public int Sizes
{
set
{
sizes = value * 1024;
}
}
/// <summary>
/// 設定上傳檔案的類型,如:jpg|gif|bmp
/// </summary>
public string FileType
{
set
{
fileType = value;
}
}
/// <summary>
/// 上傳圖片
/// </summary>
/// <param name="name">上傳控制項名稱</param>
/// <param name="creatDirectory">true則以目前時間建立檔案夾,false則為設定的檔案夾</param>
/// <returns>返回上傳圖片的相對路徑</returns>
public string fileSaveAs(System.Web.UI.HtmlControls.HtmlInputFile name,bool creatDirectory)
{
try
{
string filePath=null;
//以目前時間修改圖片的名字或建立檔案夾的名字
string modifyFileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
//獲得網站的實體路徑
string uploadFilePath = null;
//如果為true則以目前時間建立檔案夾,否則為設定的檔案夾
if(creatDirectory)
{
uploadFilePath = System.Web.HttpContext.Current.Server.MapPath(".") + @"\" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + @"\";
}
else
{
uploadFilePath = System.Web.HttpContext.Current.Server.MapPath(".") + path;
}
//獲得檔案的上傳的路徑
string sourcePath=name.Value.Trim();
//判斷上傳檔案是否為空白
if(sourcePath == "" || sourcePath == null)
{
message("您沒有上傳資料呀,是不是搞錯了呀!");
return null;
}
//獲得副檔名
string tFileType = sourcePath.Substring(sourcePath.LastIndexOf(".")+1);
//獲得上傳檔案的大小
long strLen = name.PostedFile.ContentLength;
//分解允許上傳檔案的格式
string[] temp = fileType.Split('|');
//設定上傳的檔案是否是允許的格式
bool flag = false;
//判斷上傳檔案大小
if(strLen >= sizes)
{
message("上傳的圖片不能大於" + sizes + "KB");
return null;
}
//判斷上傳的檔案是否是允許的格式
foreach(string data in temp)
{
if(data == tFileType)
{
flag = true ;
break;
}
}
//如果為真允許上傳,為假則不允許上傳
if(!flag)
{
message("目前本系統支援的格式為:"+fileType);
return null;
}
System.IO.DirectoryInfo dir=new System.IO.DirectoryInfo(uploadFilePath);
//判斷檔案夾否存在,不存在則建立
if(!dir.Exists)
{
dir.Create();
}
filePath = uploadFilePath + modifyFileName + "." + tFileType;
name.PostedFile.SaveAs(filePath);
filePath = path + modifyFileName + "." + tFileType;
return filePath;
}
catch
{
//異常
message("出現未知錯誤!");
return null;
}
}
private void message(string msg,string url)
{
System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('"+msg+"');window.location='"+url+"'</script>");
}
private void message(string msg)
{
System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('"+msg+"');</script>");
}
}
}