Asp.net 上傳圖片,儲存路徑到資料庫
阿新 • • 發佈:2019-01-23
本方法相對獨立,直接放到頁面中,呼叫即可,返回上傳後圖片的路徑,圖片名稱已經修改為純數字+字尾名
/// <summary> /// 上傳檔案,返回儲存的路徑/檔名 /// </summary> /// <param name="fupload">web控制元件</param> /// <param name="Folder">資料夾路徑</param> /// <returns></returns> private string UploadFile(FileUpload fupload, string Folder) { string strNewUrl = ""; string strFileOldName = ""; string strFileNewName = ""; strFileOldName = fupload.FileName; if (strFileOldName.Trim().Length == 0) { return ""; } string fileType = strFileOldName.Substring(strFileOldName.LastIndexOf('.')); if (fileType.ToUpper() != ".JPG" && fileType.ToUpper() != ".GIF" && fileType.ToUpper() != ".PNG" && fileType.ToUpper() != ".JPEG")//此處可換成其他的,判斷限制上傳檔案的格式。 { Common.MessageBoxCancel(this.Page, "請選擇正確圖片格式(JPG、GIF、PNG、JPEG)!", HttpContext.Current.Request.Url.ToString()); return ""; } strFileNewName = Common.GetNo() + fileType; try { string newPath = Folder; if (!Directory.Exists(HttpContext.Current.Server.MapPath(newPath))) { //HttpContext.Current.Server.MapPath(相對路徑):把相對路徑轉為伺服器上的絕對路徑。 //File.Exists(絕對路徑):檢查是否存在絕對路徑指向的檔案或目錄。 System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(newPath)); //System.IO.Directory.CreateDirectory(資料夾絕對路徑):建立絕對路徑資料夾。 } strNewUrl = newPath + strFileNewName; //上傳檔案並指定上傳目錄的路徑 fupload.PostedFile.SaveAs(Server.MapPath(newPath) + strFileNewName); return strNewUrl; } catch (Exception ex) { return strNewUrl = "出現異常,無法上傳!" + ex.Message; } }