Пример #1
0
        public async Task <IActionResult> Post([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 addedPlan = await _plansService.AddPlanAsync(model.Title, model.Description, url, userId);

            if (addedPlan != 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 = $"{addedPlan.Title} has been added successfully!",
                    Record = addedPlan
                }));
            }

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