public IActionResult AddS(StudentsAddSViewModel model) { if (ModelState.IsValid) { string uniqueFileName = null; if (model.Photos != null && model.Photos.Count > 0) { uniqueFileName = ProcessUploadedFile(model); } Student newStudent = new Student { Name = model.Name, Email = model.Email, ClassName = model.ClassName, PhotoPath = uniqueFileName, }; _studentRepository.Add(newStudent); //Student newStudent = _studentRepository.Add(student); return(RedirectToAction("Data", new { id = newStudent.Id })); } return(View()); }
/// <summary> /// 将图片保存到指定的路径中,并返回唯一的文件名 /// </summary> /// <returns></returns> private string ProcessUploadedFile(StudentsAddSViewModel model) { string uniqueFileName = null; if (model.Photos.Count > 0) { foreach (var photo in model.Photos) { //将图片上传到WWWROOT的img文件夹中 //要获取到wwwroot文件夹的路径,我们需要注入ASP.NET Core提供的HostingEnvironment服务 //通过HostingEnvironment服务获取到wwwroot文件夹路径 string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "img"); //为了保证文件名是唯一,在文件夹名后加一个新的GUID值和一个下划线 uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); //使用了非托管资源,所以需要手动进行释放 using (var fileStream = new FileStream(filePath, FileMode.Create)) { //使用IFormFile接口提供的CopyTo()方法将文件复制到wwwroot/img文件夹中 photo.CopyTo(fileStream); } // photo.CopyTo(new FileStream(filePath, FileMode.Create)); } } return(uniqueFileName); }