private List <PetImage> GetImagesFromRequest(HttpFileCollectionBase files) { List <PetImage> petImages = new List <PetImage>(); for (int i = 0; i < files.Count; i++) { //create the byte[] which is what EF uses for files byte[] fileBytes = new byte[files[i].ContentLength]; //copy byte array content of file files[i].InputStream.Read(fileBytes, 0, fileBytes.Length); PetImage pi = new PetImage { Name = files[i].FileName, Size = files[i].ContentLength, Type = files[i].ContentType, Image = fileBytes, CreatedOn = DateTime.Now, IsDisplayPic = true, //Implicitly assigned by EF: Id (PK) and PetId (FK). Lost of things happening implicitly with EF }; petImages.Add(pi); } Debug.WriteLine("The petImages list: "); Debug.WriteLine(string.Join(",", petImages)); return(petImages); }
public async Task <IActionResult> AddImage(PetImageViewModel model) { if (ModelState.IsValid) { var path = string.Empty; if (model.ImageFile != null) { path = await _imageHelper.UploadImageAsync(model.ImageFile); } var petImage = new PetImage { ImageUrl = path, Pet = await _context.Pets.FindAsync(model.Id) }; _context.PetImages.Add(petImage); await _context.SaveChangesAsync(); return(RedirectToAction($"{nameof(DetailsPet)}/{model.Id}")); } return(View(model)); }
public async Task <IHttpActionResult> UploadImage(int id) { // This endpoint only supports multipart form data if (!Request.Content.IsMimeMultipartContent("form-data")) { return(StatusCode(HttpStatusCode.UnsupportedMediaType)); } // Call service to perform upload, then attatch image url FileModel uploadedFile = await _fileService.UploadSingleFile(Request.Content); if (uploadedFile != null) { PetImage petImage = new PetImage { PetID = id, ImageURL = uploadedFile.FileUrl }; _petService.AddPetImage(id, petImage); return(Ok(petImage)); } // Otherwise return(BadRequest()); }
public async Task <ActionResult <PetImage> > Post( [FromBody] PetImage model, [FromServices] DataContext context ) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //Add + Salvar DB context.PetImages.Add(model); await context.SaveChangesAsync(); return(Ok(model)); } catch (Exception) { return(BadRequest(new { message = "Não foi possível cadastrar a imagem do produto." })); } }
public async Task <ActionResult <PetImage> > Put( int id, [FromBody] PetImage model, [FromServices] DataContext context) { try { //validar id produto passado if (id != model.Id) { return(NotFound(new { message = "Nenhuma imagem encontrada" })); } //Valida model if (!ModelState.IsValid) { return(BadRequest(model)); } //Update DB context.Entry <PetImage>(model).State = EntityState.Modified; await context.SaveChangesAsync(); return(Ok(model)); //poderia retornar uma mensagem de sucesso. } catch (DbUpdateConcurrencyException) { return(BadRequest(new { message = "Esse registro já foi atualizado" })); } catch (Exception) { return(BadRequest(new { message = "Não foi possível atualizar a imagem do produto" })); } }
public PetImage AddPetImage(int petID, PetImage image) { db.PetImages.Add(image); db.SaveChanges(); return(image); }
public PetImageModel(PetImage petImage) { Id = petImage.Id; PetId = petImage.PetId; Name = petImage.Name; Description = petImage.Description; Path = petImage.Path; }
public PetImageViewModel PetImageToPetImageViewModel(PetImage petImage) { return(new PetImageViewModel { Id = petImage.Id, Code = petImage.Code.ToString(), ImageUrl = _generalHelper.FormatSiteImageUrl(petImage.ImageUrl), IsProfileImage = petImage.IsProfileImage }); }
public async Task CreateAsync(CreatePetInputModel input, string userId, string imagePath) { var breed = this.breedsRepo.All().FirstOrDefault(x => x.Id == input.BreedId); if (input.TypeOfPet != breed.TypeOfPet) { throw new Exception($"Invalid breed! Choose valid {input.TypeOfPet} breed!"); } var pet = new Pet() { Name = input.Name, Sex = input.Sex, TypeOfPet = input.TypeOfPet, BreedId = input.BreedId, BirthDate = input.BirthDate, StartOfPeriod = input.StartOfPeriod, EndOfPeriod = input.EndOfPeriod, Description = input.Description, OwnerId = userId, }; Directory.CreateDirectory($"{imagePath}/pets/"); foreach (var image in input.Images) { var extension = Path.GetExtension(image.FileName).TrimStart('.'); if (!this.allowedExtensions.Any(x => extension.EndsWith(x))) { throw new Exception($"Invalid image extension {extension}"); } var dbImage = new PetImage { AddedByUserId = userId, Extension = extension, }; pet.PetImages.Add(dbImage); var physicalPath = $"{imagePath}/pets/{dbImage.Id}.{extension}"; using Stream fileStream = new FileStream(physicalPath, FileMode.Create); await image.CopyToAsync(fileStream); } await this.petsRepo.AddAsync(pet); await this.petsRepo.SaveChangesAsync(); }
public async Task <IActionResult> UploadImage(PetImage model) { var formFile = model.ImageFile; var originalFilename = Path.GetFileName(formFile.FileName); var newFileName = Path.GetFileNameWithoutExtension(formFile.FileName) + "_" + model.PetId + ".jpg"; var uploadpath = Path.Combine(_appEnvironment.WebRootPath, "images"); //using (var fileStream = new FileStream(Path.Combine(uploadpath, newFileName), FileMode.Create)) // { var bitMap = new Bitmap(formFile.OpenReadStream()); Size original = new Size(bitMap.Width, bitMap.Height); int maxSize = 300; float percent = (new List <float> { (float)maxSize / (float)original.Width, (float)maxSize / (float)original.Height }).Min(); Size resultSize = new Size((int)Math.Floor(original.Width * percent), (int)Math.Floor(original.Height * percent)); Bitmap target = new Bitmap(resultSize.Width, resultSize.Height); Graphics graphic = Graphics.FromImage(target); graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; graphic.SmoothingMode = SmoothingMode.HighQuality; graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; graphic.CompositingQuality = CompositingQuality.HighQuality; graphic.DrawImage(bitMap, 0, 0, resultSize.Width, resultSize.Height); target.Save(Path.Combine(uploadpath, newFileName), ImageFormat.Jpeg); //await formFile.CopyToAsync(fileStream); string filePath = "images\\" + newFileName; string baseUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}"; //} var pet = _context.Pets.FirstOrDefault(x => x.Id == model.PetId); if (pet != null) { pet.PetImage = newFileName; _context.Update(pet); await _context.SaveChangesAsync(); } // process uploaded files // Don't rely on or trust the FileName property without validation. return(RedirectToAction("Details", "Pets", new { id = model.PetId })); }
public bool AttatchProfileImage(int petID, int petImageID) { Pet pet = db.Pets.Find(petID); PetImage petImage = db.PetImages.Find(petImageID); if (petImage == null) { return(false); } pet.PetImage = petImage; db.SaveChanges(); return(true); }
public ActionResult AddPetImage(FormCollection collection, PetImage pi) { var CB_Uri = collection["txturi"]; var CB_PetId = int.Parse(collection["petid"]); if (string.IsNullOrEmpty(CB_Uri)) { ViewData["Loi1"] = " Đường dẫn không được để trống "; } else { pi.Uri = CB_Uri; pi.PetId = CB_PetId; _dbContext.PetImages.Add(pi); _dbContext.SaveChanges(); return(RedirectToAction("PetImage", "Admin")); } return(this.AddPetImage()); }
public JsonResult AddImagesToPet(Guid Id) { var _db = new SquareDanceDb(); try { foreach (string file in Request.Files) { var fileContent = Request.Files[file]; if (fileContent.ContentLength > 0) { var fileName = Guid.NewGuid().ToString() + fileContent.FileName; var path = Path.Combine(Server.MapPath("~/Pic/"), fileName); fileContent.SaveAs(path); var petImage = new PetImage(); { petImage.PetId = Id; petImage.Path = Path.Combine("http://www.liar114.com/Pic/", fileName); petImage.Name = fileName; petImage.Description = "asfasd"; } _db.PetImage.Add(petImage); } } _db.SaveChanges(); return(Json(_PetImagesDetail(Id), JsonRequestBehavior.AllowGet)); } catch (Exception e) { logger.Error("An error occurred while AddImagesToPet. Error: " + e); Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json("错误", JsonRequestBehavior.AllowGet)); } finally { _db.Dispose(); } }
public JsonResult AddDog(PetModel model) { var _db = new SquareDanceDb(); try { var newDog = new Pet(model); foreach (string file in Request.Files) { var fileContent = Request.Files[file]; if (fileContent.ContentLength > 0) { var fileName = Guid.NewGuid().ToString() + fileContent.FileName; var path = Path.Combine(Server.MapPath("~/Pic/"), fileName); fileContent.SaveAs(path); var petImage = new PetImage(); { petImage.PetId = newDog.Id; petImage.Path = Path.Combine("http://www.liar114.com/Pic/", fileName); petImage.Name = fileName; petImage.Description = "asfasd"; } newDog.PetImages.Add(petImage); } } newDog = _db.Pet.Add(newDog); _db.SaveChanges(); } catch (Exception e) { logger.Error("An error occurred while UploadDog. Error: " + e); } finally { _db.Dispose(); } return(Json(new { Success = true }, JsonRequestBehavior.AllowGet)); }