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; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// 上傳檔案到指定的檔案夾 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSure_Click(object sender, EventArgs e) { //string phName = this.txtName.Text; //string phType = this.ddlType.SelectedValue; if (this.myFile.PostedFile != null) //myFile是上傳控制項的名稱 { string photoName1 = myFile.PostedFile.FileName; //擷取初始檔案名稱 int i = photoName1.LastIndexOf("."); //取得檔案名稱中最後一個"."的索引 string newext = photoName1.Substring(i); //擷取副檔名 if (newext != ".gif" && newext != ".jpg" && newext != ".jpeg" && newext != ".bmp" && newext != ".png") { Response.Write("檔案格式不正確!"); Response.End(); } DateTime now = DateTime.Now; //擷取系統時間 string classid = DateTime.Now.Year.ToString(); //根據年份判斷在該路徑下是否存在以當年年份檔案夾 否則將建立以該年份的檔案夾 if (!Directory.Exists(HttpContext.Current.Server.MapPath("photos/") + "//" + classid)) //HttpContext.Current.Server.MapPath(相對路徑):把相對路徑轉為伺服器上的絕對路徑。File.Exists(絕對路徑):檢查是否存在絕對路徑指向的檔案或目錄。 { System.IO.Directory.CreateDirectory(@HttpContext.Current.Server.MapPath("photos/") + "//" + classid); //System.IO.Directory.CreateDirectory(檔案夾絕對路徑):建立絕對路徑檔案夾。 } string photoName2 = now.Millisecond.ToString() + "_" + myFile.PostedFile.ContentLength.ToString() + newext; //重新為檔案命名,時間毫秒部分+檔案大小+副檔名 myFile.PostedFile.SaveAs(Server.MapPath("photos//"+classid+"//" + photoName2)); // 儲存檔案到路徑,用Server.MapPath()取當前檔案的絕對目錄.在asp.net裡"/"必須用"//"代替 } } /// <summary> /// 這是一個button控制項指定在某目錄下建立檔案夾的樣本,可供參考按照年月或不同的人上傳在不同的檔案夾裡 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnCreateBag_Click(object sender, EventArgs e) { string classid = DateTime.Now.Year.ToString(); if (!Directory.Exists(HttpContext.Current.Server.MapPath("photos/") + "//" + classid)) //HttpContext.Current.Server.MapPath(相對路徑):把相對路徑轉為伺服器上的絕對路徑。File.Exists(絕對路徑):檢查是否存在絕對路徑指向的檔案或目錄。 { System.IO.Directory.CreateDirectory(@HttpContext.Current.Server.MapPath("photos/") + "//" + classid); //System.IO.Directory.CreateDirectory(檔案夾絕對路徑):建立絕對路徑檔案夾。 } else { Response.Write("<script language=javascript>alert('檔案夾已經存在')</script>"); } } } |