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; /// <summary> /// Summary description for UploadFile /// </summary> public class UploadFile { private string[] AllowFileType; //所允許的檔案類型 private double FileLength; //所允許的檔案大小(KB) private string SavePath; //檔案的儲存路徑 private string SaveFile; //上傳後的檔案名稱 private string Error; //儲存錯誤資訊 private string FileExtesion; //上傳檔案的副檔名 /// <summary> /// 建構函式 /// </summary> /// <param name="allFileType">允許的檔案類型,多個以","分開</param> /// <param name="fileLength">檔案大小</param> /// <param name="savePath">儲存路徑</param> public UploadFile(string allFileType, double fileLength, string savePath) { char[] sp = { ',' }; AllowFileType = allFileType.Split(sp); FileLength = fileLength * 1024; SavePath = savePath; } /// <summary> /// 返回產生的檔案名稱 /// </summary> public string FileName { get { return SaveFile; } } /// <summary> /// 返回出錯資訊 /// </summary> public string ErrorMessage { get { return Error; } } /// <summary> /// 根據SavePath,組建檔案名 /// </summary> /// <returns></returns> private string MakeFileName(string fileType,string fileName) { string file = this.SavePath + "\\" + DateTime.Now.ToString("yyMMddhhmmss") + fileName; while (File.Exists(file)) { file = this.SavePath + "\\" + DateTime.Now.ToString("yyMMddhhmmss") + fileName; } return file; } /// <summary> /// 檢查檔案類型 /// </summary> /// <param name="fileEx">MIME內容</param> /// <returns></returns> private bool CheckFileExt(string fileEx) { bool result = false; for (int i = 0; i < this.AllowFileType.Length; i++) { if (fileEx.IndexOf(this.AllowFileType[i].ToLower()) > -1) { result = true; break; } } return result; } public bool UpLoad(System.Web.UI.WebControls.FileUpload file) { bool result = true; try { //查看檔案長度 if (file.PostedFile.ContentLength > (this.FileLength)) { this.Error = "檔案大小超出範允許的範圍!"; return false; } string fileName = Path.GetFileName(file.PostedFile.FileName); this.FileExtesion = Path.GetExtension(fileName); if (!CheckFileExt(this.FileExtesion.ToLower())) { this.Error = "檔案類型" + this.FileExtesion + "不允許!"; return false; } //取得要儲存的檔案名稱 string UpFile = this.MakeFileName(this.FileExtesion, fileName); //儲存檔案 file.PostedFile.SaveAs(UpFile); //返迴文件名 this.SaveFile = Path.GetFileName(UpFile); } catch (Exception e) { result = false; this.Error = e.Message; } return result; } } |