public IActionResult CreateImage([FromBody] ImageForCreate imageForCreate) { if (imageForCreate == null) { return(BadRequest()); } if (!ModelState.IsValid) { // return 422 - Unprocessable Entity when validation fails return(new NonprocessableEntityResult(ModelState)); } // Automapper maps only the Title in our configuration var imageEntity = Mapper.Map <Entities.Image>(imageForCreate); // Create an image from the passed-in bytes (Base64), and // set the filename on the image // get this environment's web root path (the path // from which static content, like an image, is served) var webRootPath = _hostingEnvironment.WebRootPath; // create the filename string fileName = Guid.NewGuid().ToString() + ".jpg"; // the full file path var filePath = Path.Combine($"{webRootPath}/images/{fileName}"); // write bytes and auto-close stream System.IO.File.WriteAllBytes(filePath, imageForCreate.Bytes); // fill out the filename imageEntity.FileName = fileName; // Set the ownerId on the imageEntity var ownerId = User.Claims.FirstOrDefault(c => c.Type == "sub").Value; imageEntity.OwnerId = ownerId; // add and save. _galleryRepository.AddImage(imageEntity); if (!_galleryRepository.Save()) { throw new Exception($"Adding an image failed on save."); } var imageToReturn = Mapper.Map <Image>(imageEntity); return(CreatedAtRoute("GetImage", new { id = imageToReturn.Id }, imageToReturn)); }
public async Task <IActionResult> AddImage(AddImageViewModel addImageViewModel) { if (!ModelState.IsValid) { return(View()); } // create an ImageForCreation instance var imageForCreation = new ImageForCreate() { Title = addImageViewModel.Title }; // take the first (only) file in the Files list var imageFile = addImageViewModel.Files.First(); if (imageFile.Length > 0) { using (var fileStream = imageFile.OpenReadStream()) using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); imageForCreation.Bytes = ms.ToArray(); } } // serialize it var serializedImageForCreation = JsonConvert.SerializeObject(imageForCreation); // call the API var httpClient = await _imageGalleryHttpClient.GetClient(); var response = await httpClient.PostAsync( $"api/images", new StringContent(serializedImageForCreation, System.Text.Encoding.Unicode, "application/json")) .ConfigureAwait(false); if (response.IsSuccessStatusCode) { return(RedirectToAction("Index")); } throw new Exception($"A problem happened while calling the API: {response.ReasonPhrase}"); }