コード例 #1
0
        public async Task <IActionResult> Picture(int carId, PictureViewModel model)
        {
            if (carId != model.CarId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                var car = await _context.Cars
                          .FirstOrDefaultAsync(m => m.Id == carId);

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

                try
                {
                    _fileProvider.FileDelete(car.Picture);

                    string extension = Path.GetExtension(model.File.FileName);
                    var    directory = "/images";
                    var    fileName  = $"{Guid.NewGuid().ToString()}{extension}";
                    var    filePath  = $"{directory}/{fileName}";

                    car.Picture = filePath;
                    _fileProvider.ImageFileCreate(directory, fileName, model.File.OpenReadStream());
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Details), new { id = carId }));
                }
                catch (Exception)
                {
                    _fileProvider.FileDelete(car.Picture);
                    throw;
                }
            }

            return(View(model));
        }