Asp.net_使用FileUpload控制元件上傳檔案通用方法分享
阿新 • • 發佈:2018-12-30
FileUpload控制元件是.net自帶的控制元件,相信大家上傳檔案的時候在不借助第三方控制元件時還是非常方便的,現在博主就拿實際專案中總結的通用方法給大家分享一下,相信對初學者還是很有幫助的(ls_man)。
/// <summary>使用FileUpload控制元件上傳檔案</summary> /// <param name="page">this</param> /// <param name="path">檔案儲存目錄,相對路徑示例:"~/UploadFile",絕對路徑示例:"E:\UploadFile",提示:web路徑中用斜槓,檔案系統中用反斜槓</param> /// <param name="fu">FileUpload</param> /// <param name="checkFileName">是否檢查檔名,true表示不允許檔名重複,false則檔名加時間重新命名</param> /// <param name="allowTypes">允許上傳的檔案型別,副檔名,例:"xls",不限制類型傳null即可</param> /// <returns>檔案絕對路徑</returns> /// <remarks>版權所有http://blog.csdn.net/ls_man</remarks> public static string UploadFileToServer(Page page, String path, FileUpload fu, Boolean checkFileName, params String[] allowTypes) { //記錄檔名 string fileName = fu.FileName; //是否選擇檔案 if (string.IsNullOrEmpty(fileName)) { MsgBox.Alert(page, "請先選擇檔案!"); return null; } //記錄副檔名 string fileType = fileName.Substring(fileName.LastIndexOf('.') + 1); //判斷副檔名是否允許 bool typeRight = false; //記錄允許上傳的檔案型別 string allowType = ""; //是否指定檔案型別 if (allowTypes != null) { //遍歷允許檔案型別陣列 for (int i = 0; i < allowTypes.Length; i++) { //已判斷為允許則不再判斷 if (!typeRight) { //副檔名大小轉換判斷是否符合要求 if (fileType == allowTypes[i] || fileType.ToLowerInvariant() == allowTypes[i] || fileType.ToUpperInvariant() == allowTypes[i]) { //符合要求則設定為允許 typeRight = true; } } //記錄允許上傳的檔案型別 allowType += "." + allowTypes[i] + " | "; } //刪除最後一個分隔符 allowType = allowType.Remove(allowType.LastIndexOf("|")); } //未指定檔案型別時 else { //直接設定為允許 typeRight = true; } //副檔名不正確 if (!typeRight) { //提示允許上傳的檔案型別 MsgBox.Alert(page, "檔案格式不正確,請選擇副檔名為[ " + allowType + " ]的檔案!"); return null; } //是否可以正常獲取檔案 if (fu.PostedFile.ContentLength == 0) { MsgBox.Alert(page, "找不到選擇的檔案,請重新選擇!"); return null; } //目錄絕對路徑 string dirRootPath = ""; //檔案路徑異常處理 try { //如果路徑是相對路徑 if (!Path.IsPathRooted(path)) { //目錄相對路徑轉絕對路徑 dirRootPath = HttpContext.Current.Server.MapPath(@"" + path + "/").Trim(); } else { //儲存路徑 dirRootPath = path; } //檔案上傳目錄是否存在 DirectoryInfo dirInfo = new DirectoryInfo(dirRootPath); if (!dirInfo.Exists) { //不存在則建立此目錄 dirInfo.Create(); } } catch (Exception pathError) { //異常彈窗提示 MsgBox.Alert(page, "錯誤:" + pathError.Message); return null; } //記錄檔案絕對路徑 string fileRootPath = ""; //需要檢查檔名是否重複時 if (checkFileName) { //檔案絕對路徑 fileRootPath = Path.Combine(dirRootPath, fileName); //檔名已存在 if (File.Exists(fileRootPath)) { //提示改名 MsgBox.Alert(page, "伺服器已存在同名檔案,請修改檔名後重試!"); return null; } } else { //選擇的檔案按時間重新命名 string newFileName = fileName.Remove(fileName.LastIndexOf(".")) + DateTime.Now.ToString("yyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + "." + fileType; //檔案絕對路徑 fileRootPath = Path.Combine(dirRootPath, newFileName); } //上傳至伺服器 fu.SaveAs(fileRootPath); //返回檔案絕對路徑 return fileRootPath; }
【End】