.net core圖片上傳詳解


首先有一點先確認下.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
                });
            }
        }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM