首先有一點先確認下.net core 不存在Server.MapPath這個方法所以想引用服務器根目錄或者web根目錄應該在controller中引入IWebHostEnvironment對象
private readonly IWebHostEnvironment _hostingEnvironment; public AdvertisementsController(IWebHostEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; }
/// <summary> /// 上傳圖片 /// </summary> /// <returns></returns> public async Task<ActionResult> Upload() { try { IFormFileCollection files = Request.Form.Files; var file = files[0]; //獲取文件名后綴 string extName = Path.GetExtension(file.FileName).ToLower(); //獲取保存目錄的物理路徑 if (System.IO.Directory.Exists(_hostingEnvironment.WebRootPath + "/upload/") == false)//如果不存在就創建images文件夾 { System.IO.Directory.CreateDirectory(_hostingEnvironment.WebRootPath + "/upload/"); } string path = _hostingEnvironment.WebRootPath + "/upload/"; //path為某個文件夾的絕對路徑,不要直接保存到數據庫 // string path = "F:\\TgeoSmart\\Image\\"; //生成新文件的名稱,guid保證某一時刻內圖片名唯一(文件不會被覆蓋) string fileNewName = Guid.NewGuid().ToString(); string ImageUrl = path + fileNewName + extName; //SaveAs將文件保存到指定文件夾中 using (var stream = new FileStream(ImageUrl, FileMode.Create)) { await file.CopyToAsync(stream); } //此路徑為相對路徑,只有把相對路徑保存到數據庫中圖片才能正確顯示(不加~為相對路徑) string url = "\\upload\\" + fileNewName + extName; return Json(new { Result = true, Data = url }); } catch (Exception exception) { return Json(new { Result = false, exception.Message }); } }