using System;
using System.Web;
using System.IO;
namespace leo
{
/// <summary>
/// 檔案上傳類
/// 作者:leo
/// 製作時間:2006-2-13 最後修改於2007-6-25
/// </summary>
public class UploadFile
{
public UploadFile(HttpPostedFile PostedFile)
{
FileObj = PostedFile;
}
private HttpPostedFile FileObj;
private int maxSize = 150 * 1024; //預設150KB
private string filesType = ".jpeg|.jpg|.gif"; //預設檔案類型
private bool oldFileName = false; //是否採用原檔案名稱
private string filesPath = ""; //設定檔案夾路徑
private string Eror = ""; //錯誤資訊
private int errorNum = 0; //錯誤碼
private string savaFileName = ""; //上傳成功後的檔案名稱
//屬性區
public int MaxSizeKB
{
get{ return maxSize / 1024; }
set{ maxSize = value * 1024;}
}
public string FilesType
{
get{ return filesType; }
set{ filesType = value.ToLower();}
}
public string FilesPath
{
get{ return filesPath; }
set{ filesPath = value;}
}
public string SavaFileName
{
get{ return savaFileName; }
set{ savaFileName = value;}
}
public string SaveEror
{
get{ return Eror; }
}
public int ErrorNum
{
get { return errorNum; }
}
public bool OldFileName
{
get{ return oldFileName; }
set{ oldFileName = value;}
}
//方法區
private string GetNewFileName(string FlieExtension)
{
Random rd = new Random();
int rnum = rd.Next(100, 999);
string dt = DateTime.Now.ToString("yyyyMMddhhmmss");
return dt + rnum.ToString() + FlieExtension;
}
public bool SaveFile()
{
if (FileObj != null)
{
try
{
string strFileURLName = FileObj.FileName; //上傳檔案原URL
string strFileName = Path.GetFileName(strFileURLName); //上傳檔案原名
string strFlieExtension = Path.GetExtension(strFileURLName).ToLower(); //上傳檔案原副檔名
if (FileObj.ContentLength == 0)
{
Eror = "您上傳的檔案為空白";
errorNum = 2;
return false;
}
if (FileObj.ContentLength > maxSize)
{
Eror = "上傳檔案超過限定大小";
errorNum = 3;
return false;
}
string[] fType = filesType.Split('|');
bool ok = false;
for (int i = 0; i < fType.Length; i++)
{
if (fType[i] == strFlieExtension)
ok = true;
}
if (!ok)
{
Eror = "上傳檔案類型不是程式允許的類型";
errorNum = 4;
return false;
}
if(!Directory.Exists(filesPath))
{
Eror = "檔案儲存體的目錄不存在";
errorNum = 5;
return false;
}
string NewFileName;
if (!oldFileName)
{
NewFileName = GetNewFileName(strFlieExtension);
}
else
NewFileName = strFileName;
try
{
FileObj.SaveAs(Path.Combine(filesPath,NewFileName));
}
catch
{
Eror = "隱藏檔時發生錯誤,可能是該目錄沒有許可權";
errorNum = 6;
return false;
}
savaFileName = NewFileName;
Eror = "";
errorNum = 0;
return true;
}
catch(Exception e)
{
Eror = e.ToString();
errorNum = 9;
return false;
}
}
else
{
Eror = "沒有檔案被上傳";
errorNum = 1;
return false;
}
}
}
}