public IActionResult Create() { ViewData["UserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id"); UploadProjectPhotoViewModel viewModel = new UploadProjectPhotoViewModel(); viewModel.Project = new Project(); return(View(viewModel)); }
public async Task <IActionResult> Create(UploadProjectPhotoViewModel viewModel) { ModelState.Remove("Project.UserId"); var user = await GetCurrentUserAsync(); viewModel.Project.UserId = user.Id; viewModel.Project.User = user; viewModel.Project.DateCreated = DateTime.Now; // If you want to check errors in model state use the code below: var errors = ModelState.Values.SelectMany(v => v.Errors); if (ModelState.IsValid) { if (viewModel.ImageFile != null) { // don't rely on or trust the FileName property without validation //**Warning**: The following code uses `GetTempFileName`, which throws // an `IOException` if more than 65535 files are created without // deleting previous temporary files. A real app should either delete // temporary files or use `GetTempPath` and `GetRandomFileName` // to create temporary file names. var fileName = Path.GetFileName(viewModel.ImageFile.FileName); Path.GetTempFileName(); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images/projectpictures", fileName); //var filePath = Path.GetTempFileName(); using (var stream = new FileStream(filePath, FileMode.Create)) { await viewModel.ImageFile.CopyToAsync(stream); // validate file, then move to CDN or public folder } viewModel.Project.ImagePath = viewModel.ImageFile.FileName; } _context.Add(viewModel.Project); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(viewModel.Project)); }