public InsertPostModel InsertPost(string text, IFormFile file) { try { string fileName = null; if (file != null) { string uploadsFolder = Path.Combine(_environment.WebRootPath, "images"); fileName = Guid.NewGuid().ToString() + "_" + file.FileName; string filePath = Path.Combine(uploadsFolder, fileName); file.CopyTo(new FileStream(filePath, FileMode.Create)); } Post obj = new Post() { Text = text, PhotoPath = fileName, UserId = UserId, Time = DateTime.Now }; _dbcontext.Post.Add(obj); _dbcontext.SaveChanges(); var user = _dbcontext.User.Single(c => c.Id == obj.UserId); InsertPostModel model = new InsertPostModel() { Id = obj.Id, NameSurname = user.Name + " " + user.Surname, PPPath = user.PhotoPath, Time = obj.Time, Text = obj.Text, PhotoPath = obj.PhotoPath, LikeCount = _dbcontext.LikeDislike.Where(c => c.PostId == obj.Id && c.LikeOrDislike).Count(), DislikeCount = _dbcontext.LikeDislike.Where(c => c.PostId == obj.Id && !c.LikeOrDislike).Count(), CommentCount = obj.Comments.Count }; return(model); } catch (Exception e) { return(null); } }
public async Task <IActionResult> Create([Bind("Id,SongId,ArtistId,ViewCount,YoutubeLink,PdfFilePath,Reviewed")] InsertPostModel insertPost, List <IFormFile> files) { var isNormalYoutubeLink = Regex.IsMatch(insertPost.YoutubeLink, "((http(s)?://)(www.)?)?youtube.com\\/watch\\?v=([^#&?]).*"); if (ModelState.IsValid && isNormalYoutubeLink) { var uploads = Path.Combine(_webHostEnvironment.WebRootPath, "uploads"); var post = new Post { ArtistId = insertPost.ArtistId, SongId = insertPost.SongId, Reviewed = false, ViewCount = 0 }; foreach (var file in files) { if (file.Length > 0) { var directory = Path.GetDirectoryName(uploads); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var fileName = Path.GetRandomFileName(); fileName = fileName.Replace(".", "a"); fileName += ".pdf"; var fullPath = Path.Combine(uploads, fileName); post.PdfFilePath = fileName; // If file with same name exists delete it if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } // Create new local file and copy contents of uploaded file using (var localFile = System.IO.File.OpenWrite(fullPath)) using (var uploadedFile = file.OpenReadStream()) { uploadedFile.CopyTo(localFile); } } } var videoId = insertPost.YoutubeLink.Split("=")[1]; post.UserId = User.FindFirstValue(ClaimTypes.NameIdentifier); post.YoutubeLink = $"https://www.youtube.com/embed/{videoId}"; post.ThumbnailLink = $"https://img.youtube.com/vi/{videoId}/0.jpg"; _context.Add(post); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["ArtistId"] = new SelectList(_context.Artists, "Id", "Id", insertPost.ArtistId); ViewData["SongId"] = new SelectList(_context.Songs, "Id", "Id", insertPost.SongId); return(View(insertPost)); }