public async Task <IActionResult> AddImage(AddImageViewModel addImageViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var imageForCreation = new ImageForCreationModel {
                Title = addImageViewModel.Title
            };
            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();
                    }
            }

            var serializedImageForCreation = JsonConvert.SerializeObject(imageForCreation);
            var httpClient = await _imageGalleryHttpClient.GetHttpClientAsync();

            var response = await httpClient.PostAsync(
                $"api/images",
                new StringContent(serializedImageForCreation, System.Text.Encoding.Unicode, "application/json"));

            response.EnsureSuccessStatusCode();

            return(RedirectToAction("Index"));
        }
Example #2
0
        public async Task <IActionResult> CreateImage([FromBody] ImageForCreationModel imageForCreation)
        {
            if (imageForCreation == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                // return 422 - Unprocessable Entity when validation fails
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            // Automapper maps only the Title in our configuration
            var imageEntity = _mapper.Map <Image>(imageForCreation);

            // 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, imageForCreation.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.
            await _imagesService.AddImageAsync(imageEntity);

            var imageToReturn = _mapper.Map <Image>(imageEntity);

            return(CreatedAtRoute("GetImage", new { id = imageToReturn.Id }, imageToReturn));
        }