示例#1
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.Attach(Vehicle).State = EntityState.Modified;
            carImages = _context.CarImages.Where(i => i.VehicleId == Vehicle.Id).ToList();
            if (VehiclePhotos != null && VehiclePhotos.Count() >= 4)
            {
                foreach (var photo in carImages)
                {
                    _context.CarImages.Remove(photo);
                    System.IO.File.Delete(Path.Combine(hostEnvironment.WebRootPath, photo.Image.Replace("~/", "")));
                }
                string          newImgName = null;
                List <CarImage> photos     = new List <CarImage>();
                foreach (var photo in VehiclePhotos)
                {
                    string folder = Path.Combine(hostEnvironment.WebRootPath, "CarPhotosUploaded");
                    newImgName = $"{DateTime.Now.ToString("MM_dd_yyyy_HH_mm_ss")}_{photo.FileName}";
                    string     file = Path.Combine(folder, newImgName);
                    FileStream fs   = new FileStream(file, FileMode.Create);
                    photo.CopyTo(fs);
                    fs.Close();
                    photos.Add(new CarImage {
                        Image = $"~/CarPhotosUploaded/{newImgName}"
                    });
                    if (VehiclePhotos.ElementAt(0) == photo)
                    {
                        Vehicle.ImageUrl = $"~/CarPhotosUploaded/{newImgName}";
                    }
                }
                Vehicle.Photos = photos;

                await _context.SaveChangesAsync();

                return(RedirectToPage("Profile", new { area = "User" }));
            }
            else if (VehiclePhotos != null && VehiclePhotos.Count() < 4 && VehiclePhotos.Count() > 0)
            {
                return(RedirectToPage("EditCar", new { area = "Cars", id = Vehicle.Id }));
            }
            else
            {
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("Profile", new { area = "User" }));
        }
        VehiclePhoto CreateVehiclePhoto(Image image, Int32 vehicleId)
        {
            byte[] buffer;
            using (var memoryStream = new MemoryStream()) {
                image.Save(memoryStream, new ImageFormat(image.RawFormat.Guid));
                buffer = memoryStream.ToArray();
            }
            var vehiclePhoto = new VehiclePhoto {
                ImageMimeType = "image/jpeg", Image = buffer, VehicleId = vehicleId
            };

            VehiclePhotos.Add(vehiclePhoto);
            SaveChanges();
            return(vehiclePhoto);
        }