Пример #1
0
        public async Task <IActionResult> CreateVehicle([FromBody] SaveVehicleResource vehicleResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (await repository.FindModelById(vehicleResource.ModelId) == null)
            {
                ModelState.AddModelError("ModelId", "Invalid Model Id");
                return(BadRequest(ModelState));
            }

            var vehicle = mapper.Map <SaveVehicleResource, Vehicle>(vehicleResource);

            vehicle.LastUpdate = DateTime.Now;
            repository.Add(vehicle);
            await unitOfwork.CompleteAsync();

            vehicle = await repository.GetVehicle(vehicle.Id);

            var result = mapper.Map <Vehicle, VehicleResource>(vehicle);

            return(Ok(result));
        }
        public async Task <IActionResult> UploadAsync(int vehicleId, IFormFile file)
        {
            var vehicle = await repository.GetVehicle(vehicleId, includeRelated : false);

            if (vehicle == null)
            {
                return(NotFound());
            }

            if (file == null)
            {
                return(BadRequest("Null File"));
            }
            if (file.Length == 0)
            {
                return(BadRequest("Empty File"));
            }

            if (file.Length > photoSettings.MaxBytes)
            {
                return(BadRequest("File size exceeds 10MB"));
            }
            if (!photoSettings.IsSupported(file.FileName))
            {
                return(BadRequest("Invalid file type."));
            }


            var uploadsFolderPath = Path.Combine(host.WebRootPath, "uploads");

            if (!Directory.Exists(uploadsFolderPath))
            {
                Directory.CreateDirectory(uploadsFolderPath);
            }

            var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            var filePath = Path.Combine(uploadsFolderPath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            var photo = new Photo {
                FileName = fileName
            };

            vehicle.Photos.Add(photo);
            await unitOfWork.CompleteAsync();

            return(Ok(mapper.Map <Photo, PhotoResource>(photo)));
        }