ASP.NET文件上傳,爲每個用戶建立一個上傳目錄

文件上傳界面既可以用Html的input file控件,又可以用FileUpload控件,只要將Html的input file控件加上runat="server",就會發現兩者的功能完全是一模一樣,上傳的代碼是共用的,不需要做任何改變。我想微軟在將Html控件將成標準控件時應該只是多加了runat="server"吧。放入上述兩者的任一控件後,添加一個標準的Button按鈕(Html按鈕也行,不過需要加上runat="server"),雙擊Button按鈕,產生點擊事件。在點擊事件中寫入以下代碼:

首先檢查是否已經選了文件

if (this.myFile.PostedFile != null)

{

檢查文件根目錄是否存在,不存在就要創建

if (!System.IO.Directory.Exists(Server.MapPath("~")+@"/photoes"))
{
      System.IO.Directory.CreateDirectory(Server.MapPath("~")+@"/photoes");
}

此處Server.MapPath("~")用來表示項目根目錄的物理路徑。

 

接下來創建用戶文件夾,根據用戶ID創建

if(!System.IO.Directory.Exists(Server.MapPath("~")+@"/photoes/"+userID))

{

     System.IO.Directory.CreateDirectory(Server.MapPath("~")+@"/photoes/"+userID)

}

string orignalName = this.myFile2.PostedFile.FileName;//獲取客戶機上傳文件的路徑

int lastdotlocation = orignalName.LastIndexOf(".");

string extendName = orignalName.Substring(lastdotlocation);//獲取擴展名

 if (extendName != ".gif" && extendName != ".jpg" && extendName != ".jpeg" && extendName != ".png")
{
       Response.Write("Wrong format");
       Response.End();

}//檢查文件格式

string newName = DateTime.Now.Millisecond.ToString() + "_" + myFile2.PostedFile.ContentLength.ToString() + extendName;//對文件進行重命名

myFile.PostedFile.SaveAs(Server.MapPath("~") + @"/photoes/" +userID+@"/"+ newName);

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章