コード例 #1
0
        public async Task <IActionResult> Create(NewsViewModel model)
        {
            if (ModelState.IsValid)
            {
                var newsForSave = _mapper.Map <NewsViewModel, News>(model);

                var newsFromDb = _newsData.AddNews(newsForSave);

                var fileExt = model.Wallpaper.FileName.Split('.').Last();

                string path = $"{Path.DirectorySeparatorChar}images{Path.DirectorySeparatorChar}" +
                              $"newsWallpapers{Path.DirectorySeparatorChar}"
                              + newsFromDb.Id + $".{fileExt}";


                using (var fileStream = new FileStream(_env.WebRootPath + path, FileMode.Create))
                {
                    await model.Wallpaper.CopyToAsync(fileStream);
                }

                newsFromDb.ImageUrl    = "/images/newsWallpapers/" + newsFromDb.Id + $".{fileExt}";
                newsFromDb.ReleaseTime = DateTime.Now;

                newsFromDb.ImageLocalUrl = _env.WebRootPath + path;

                newsFromDb.Author = await _userManager.GetUserAsync(User);

                _newsData.UpdateNews(newsFromDb);
                return(RedirectToAction("Index", "News"));
            }
            return(View());
        }