Exemplo n.º 1
0
        public async Task <IActionResult> Upload(int plantId, IFormFile file)
        {
            if (file == null)
            {
                return(BadRequest("Null File!"));
            }
            if (file.Length == 0)
            {
                return(BadRequest("Empty File!"));
            }
            if (file.Length > _maxFileSize)
            {
                return(BadRequest("File size is greater than " + _maxFileSize / (1024 * 1024) + " MB!"));
            }
            if (!_acceptedFileTypes.Any(f => f == Path.GetExtension(file.FileName).ToLower()))
            {
                return(BadRequest("Invalid file type! Try one of those: " + string.Join(",", _acceptedFileTypes) + "!"));
            }
            //var plant = await _context.Plants.FindAsync(plantId);
            var plant = await _context.Plants.Include(p => p.Image).SingleOrDefaultAsync(p => p.Id == plantId);

            //return Ok(_mapper.Map<Plant, PlantResource>(plant));

            if (plant == null)
            {
                return(NotFound("Plant not found!"));
            }
            if (plant.Image != null)
            {
                return(BadRequest("This plant has already an image!"));
            }

            var uploadFolderPath = Path.Combine(Host.WebRootPath, "uploads");

            if (!Directory.Exists(uploadFolderPath))
            {
                Directory.CreateDirectory(uploadFolderPath);
            }
            var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            var filePath = Path.Combine(uploadFolderPath, fileName);

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

            var image = new Image {
                FileName = fileName
            };

            _context.Images.Add(image);
            await _context.SaveChangesAsync();

            var imageInDb = _context.Images.SingleOrDefault(i => i.FileName == fileName);

            _context.Plants.SingleOrDefault(p => p.Id == plantId).Image = imageInDb;
            await _context.SaveChangesAsync();

            return(Ok(_mapper.Map <Image, ImageResource>(image)));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> PutPlant([FromRoute] int id, [Microsoft.AspNetCore.Mvc.FromBody] PlantResource plantResource)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestResult());
            }


            var plant = await _context.Plants.Include(p => p.Features).SingleOrDefaultAsync(p => p.Id == id);

            _mapper.Map <PlantResource, Plant>(plantResource, plant);
            await _context.SaveChangesAsync();

            //var result = _mapper.Map<Plant, PlantResource>(plant);
            return(new OkObjectResult(plantResource));
        }