Exemplo n.º 1
0
        public async Task <IActionResult> Put([FromForm] PlanRequest model)
        {
            string userId = User.FindFirst(ClaimTypes.NameIdentifier).Value;

            string url      = $"{_configuration["AppUrl"]}Images/default.jpg";
            string fullPath = null;

            // Check the file
            if (model.CoverFile != null)
            {
                string extension = Path.GetExtension(model.CoverFile.FileName);

                if (!allowedExtensions.Contains(extension))
                {
                    return(BadRequest(new OperationResponse <Plan>
                    {
                        Message = "Plan image is not a valid image file",
                        IsSuccess = false,
                    }));
                }

                if (model.CoverFile.Length > 500000)
                {
                    return(BadRequest(new OperationResponse <Plan>
                    {
                        Message = "Image file cannot be more than 5mb",
                        IsSuccess = false,
                    }));
                }

                string newFileName = $"Images/{Guid.NewGuid()}{extension}";
                fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", newFileName);
                url      = $"{_configuration["AppUrl"]}{newFileName}";
            }
            var oldPlan = await _plansService.GetPlanById(model.Id, userId);

            if (fullPath == null)
            {
                url = oldPlan.CoverPath;
            }

            var editedPlan = await _plansService.EditPlanAsync(model.Id, model.Title, model.Description, url, userId);

            if (editedPlan != null)
            {
                if (fullPath != null)
                {
                    using (var fs = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
                    {
                        await model.CoverFile.CopyToAsync(fs);
                    }
                }

                return(Ok(new OperationResponse <Plan>
                {
                    IsSuccess = true,
                    Message = $"{editedPlan.Title} has been edited successfully!",
                    Record = editedPlan
                }));
            }


            return(BadRequest(new OperationResponse <Plan>
            {
                Message = "Something went wrong",
                IsSuccess = false
            }));
        }