public IActionResult Add(AddViewModel model) { Image newImage = new Image { Id = Guid.NewGuid(), FileName = model.Image.FileName, Title = model.Image.Name }; if (model.Image.Length > 0) { using (var ms = new MemoryStream()) { model.Image.CopyTo(ms); var fileBytes = ms.ToArray(); newImage.ImageFile = fileBytes; } } model.NewEvent.Id = Guid.NewGuid(); model.NewEvent.StatusId = Guid.Parse("7ca65c86-0e39-465f-874d-fcb3c9183f1b"); // privremeno rjesenje, stavlja status na upcoming newImage.EventId = model.NewEvent.Id; _eventRepository.AddEvent(model.NewEvent); _imageRepository.AddImage(newImage); return(RedirectToAction("Index")); }
public async Task <IActionResult> Edit(Post post, IFormFile[] file) { if (ModelState.IsValid) { if (file != null) { var p = "wwwroot\\img\\posts\\" + post.PostId; foreach (var f in file) { if (f != null) { string ImageName = Guid.NewGuid().ToString() + Path.GetExtension(f.FileName); var path = Path.Combine(Directory.GetCurrentDirectory(), p, ImageName); using (var stream = new FileStream(path, FileMode.Create)) { await f.CopyToAsync(stream); _imageRepository.AddImage(ImageName, post.PostId, 1); } } } } _postRepository.SavePost(post); return(RedirectToAction("Index")); } pullSelect(); return(View(post)); }
public string UploadImage(IList <IFormFile> file, int taskId) { IFormFile uploadedImage = file.FirstOrDefault(); if (uploadedImage == null || uploadedImage.ContentType.ToLower().StartsWith("image/")) { MemoryStream ms = new MemoryStream(); uploadedImage.OpenReadStream().CopyTo(ms); System.Drawing.Image image = System.Drawing.Image.FromStream(ms); Image imageEntity = new Image() { ImageId = Guid.NewGuid(), TaskId = taskId, Name = uploadedImage.Name, Data = ms.ToArray(), Width = image.Width, Height = image.Height, ContentType = uploadedImage.ContentType }; return(imageRepository.AddImage(imageEntity).ToString()); } return(null); }
public async Task <IActionResult> UserImages(UserImagesViewModel model) { var userId = _userManager.GetUserId(HttpContext.User); if (ModelState.IsValid) { string uniqueFileName = null; string uploadFolder = Path.Combine("wwwroot", "img"); uniqueFileName = Guid.NewGuid().ToString() + "_" + model.ImageFile.FileName; string filePath = Path.Combine(uploadFolder, uniqueFileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { model.ImageFile.CopyTo(fileStream); } Image newImage = new Image { Path = filePath, ImageName = model.ImageName, ApplicationUserId = userId }; await _imageRepository.AddImage(newImage); } model.Images = await _imageRepository.GetImagesByUser(userId); return(View(model)); }
public HttpResponseMessage AddImage(Image image) { image.Approved = false; var i = repository.AddImage(image); var response = Request.CreateResponse <Images>(HttpStatusCode.Created, i); return(response); }
public async Task <IActionResult> AddImage(int productId, [FromForm] ProductImageForAddDto entity) { var user = await _userRepo.GetUserByUserClaims(HttpContext.User); if (user == null) { return(Unauthorized("User is Unauthorized")); } var product = await _productRepo.GetById(productId); if (product == null) { return(BadRequest("You can't add image for product not exist.")); } if (product.UserId != user.Id) { return(Unauthorized("You cannot add an image product owned by another user")); } var images = await _imageRepository.GetAllImagesForProduct(productId); if (images.Count == 4) { return(BadRequest("Sorry, you can't add more than 4 images to your product.")); } var file = entity.File; if (file == null) { return(BadRequest("Please add photo to your product.")); } var path = Path.Combine("wwwroot/images/", file.FileName); var stream = new FileStream(path, FileMode.Create); await file.CopyToAsync(stream); await stream.DisposeAsync(); var imageForAdd = _mapper.Map <ProductImage>(entity); imageForAdd.ProductId = productId; if (images.Count == 0) { imageForAdd.IsMainPhoto = true; } imageForAdd.ImageUrl = path.Substring(7); if (await _imageRepository.AddImage(imageForAdd)) { return(CreatedAtAction(nameof(GetImagesForProduct), new { productId = imageForAdd.ProductId }, imageForAdd)); } throw new Exception("Error happen when add photo to your product"); }
public IActionResult Post([FromBody] ImageViewModel data) { try { return(Ok(_repo.AddImage(data.Translate <ImageViewModel, Image>()))); } catch (Exception e) { return(BadRequest(e.StackTrace)); } }
public IActionResult Add([FromBody] AddImageRequest addImageRequest) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _imageRepository.AddImage(new Image(addImageRequest.x, addImageRequest.y, addImageRequest.image)); return(new StatusCodeResult((int)HttpStatusCode.NoContent)); }
public string AddImage(string imgName, string imgType, byte[] imgData) { ImageEntity imageEntity = new ImageEntity { name = imgName, data = imgData, type = imgType }; var imgId = _imageRepo.AddImage(imageEntity); return(imgId.ToString()); }
private async Task <Image> SaveImageAsync(string path, string image) { var imageBytes = Convert.FromBase64String(image); await File.WriteAllBytesAsync(path, imageBytes); var newImage = new Image { Path = path }; await _imageRepository.AddImage(newImage); return(newImage); }
private void DoRealImport(string uri, IImageRepository repo, IImageCollection coll) { if (!CanImportUri(uri)) { throw new InvalidOperationException(); } DirectoryInfo sourcedir = new DirectoryInfo(uri); FileInfo[] finfos = sourcedir.GetFiles(); if (coll != null) { coll.FreezeUpdates(); } foreach (FileInfo fi in finfos) { string lf = fi.FullName.ToLower(); if (lf.EndsWith(".jpg") || lf.EndsWith(".jpeg") || lf.EndsWith(".png") || lf.EndsWith(".gif") || lf.EndsWith(".tif") || lf.EndsWith(".tiff")) { // int[] wh = GetImageDimensions (fi.FullName); ImageItem.ImageInfo iinfo = new ImageItem.ImageInfo(); // iinfo.width = wh[0]; // iinfo.height = wh[1]; iinfo.width = 0; iinfo.height = 0; iinfo.filesize = (int)fi.Length; iinfo.dirname = uri; iinfo.filename = fi.Name; ImageItem iitem = new ImageItem(iinfo); iitem = repo.AddImage(iitem); if (coll != null) { coll.AddItem(iitem); } } } if (coll != null) { coll.ThawUpdates(); } }
public virtual void SaveImage(ImageViewModel image) { try { Session session = _imageRepository.GetActiveSession() ?? _imageRepository.GetLastSession(); if (session == null) { if (_imageRepository.StartSession()) { session = _imageRepository.GetActiveSession(); } else { throw new Exception("Cannot start session"); } } string baseDir = AppDomain.CurrentDomain.BaseDirectory; DirectoryInfo info = !Directory.Exists(Path.Combine(baseDir, "Images")) ? Directory.CreateDirectory(Path.Combine(baseDir, "Images")) : new DirectoryInfo(Path.Combine(baseDir, "Images")); string currentSessionStartTime = session.StartTime.ToString("dd_MM_yyyy"); string subDirectoryPath = Path.Combine(info.FullName, string.Format("{0}_{1}", currentSessionStartTime, session.Id)); DirectoryInfo subDirectory = !Directory.Exists(subDirectoryPath) ? info.CreateSubdirectory(string.Format("{0}_{1}", currentSessionStartTime, session.Id)) : new DirectoryInfo(subDirectoryPath); string path = Path.Combine(subDirectory.FullName, string.Format("{0}.png", Guid.NewGuid())); File.WriteAllBytes(path, image.Data); Image imageDb = new Image() { Session = session, Name = image.Name, Path = path }; imageDb.Session = session; _imageRepository.AddImage(imageDb); _imageRepository.Commit(); } catch (Exception) { } }
public async Task <IActionResult> Create(/*[Bind("ProductID,ProductName,ProductDescription,ImageFile,SizeID,ProductQuantity,ProductPrice")]*/ Product product) { if (ModelState.IsValid) { //after adding the product, take the product object as it has the new product id and add it to the image _product.AddProduct(product); await _product.SaveProduct(); await _image.AddImage(product); return(RedirectToAction(nameof(Index))); } ViewData["SizeName"] = _product.SelectListSize(); return(View(product)); }
public void Add_Image_ShouldCallImageRepository() { //arrange var addImageRequest = new AddImageRequest { x = 1, y = 2, image = "unit test image" }; var result = _imageController.Add(addImageRequest) as StatusCodeResult; //assert Assert.NotNull(result); Assert.Equal((int)HttpStatusCode.NoContent, result.StatusCode); A.CallTo(() => _imageRepository.AddImage(A <Image> .That.Matches(i => i.coordinates.x == addImageRequest.x && i.coordinates.y == addImageRequest.y && i.image == addImageRequest.image))) .MustHaveHappenedOnceExactly(); }
public async Task <IActionResult> Post([FromBody] ImageViewModel image) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var newImage = Mapper.Map <Image>(image); _imageRepository.AddImage(newImage); if (await _imageRepository.SaveChangesAsync()) { return(Ok(Mapper.Map <ImageViewModel>(newImage))); } return(BadRequest("Failed to save")); }
public async Task <ActionResult <ProductReadDto> > PostProduct([FromBody] /*[Bind("ProductID,ProductName,ProductDescription,ImageFile,SizeID,ProductQuantity,ProductPrice")] */ ProductCreateDto product) { if (ModelState.IsValid) { var productCreate = _mapper.Map <Product>(product); _product.AddProduct(productCreate); await _product.SaveProduct(); //BAD LOGIC <the product is saved first then the image will be inserted, //which will be bad if the project stopped for some reason //before the image was added>. await _image.AddImage(productCreate); var productRead = _mapper.Map <ProductReadDto>(productCreate); return(CreatedAtRoute(nameof(GetProduct), new { Id = productRead.ProductID }, productRead)); } return(BadRequest()); }
private void DoRealImport (string uri, IImageRepository repo, IImageCollection coll) { if (!CanImportUri (uri)) { throw new InvalidOperationException (); } DirectoryInfo sourcedir = new DirectoryInfo (uri); FileInfo[] finfos = sourcedir.GetFiles (); if (coll != null) coll.FreezeUpdates (); foreach (FileInfo fi in finfos) { string lf = fi.FullName.ToLower (); if (lf.EndsWith (".jpg") || lf.EndsWith (".jpeg") || lf.EndsWith (".png") || lf.EndsWith (".gif") || lf.EndsWith (".tif") || lf.EndsWith (".tiff")) { // int[] wh = GetImageDimensions (fi.FullName); ImageItem.ImageInfo iinfo = new ImageItem.ImageInfo (); // iinfo.width = wh[0]; // iinfo.height = wh[1]; iinfo.width = 0; iinfo.height = 0; iinfo.filesize = (int) fi.Length; iinfo.dirname = uri; iinfo.filename = fi.Name; ImageItem iitem = new ImageItem (iinfo); iitem = repo.AddImage (iitem); if (coll != null) coll.AddItem (iitem); } } if (coll != null) coll.ThawUpdates (); }
public async Task <IActionResult> UploadProductImages(IList <IFormFile> files, long productId) { if (files.Count == 0) { return(BadRequest()); } IList <Image> images = new List <Image>(); foreach (IFormFile file in files) { if (imageWriter.IsImageFile(file)) { //Create unique file name with UUID and file extension string fileName = Path.GetFileName(file.FileName); string extension = Path.GetExtension(fileName); string uniqueFileName = Guid.NewGuid().ToString() + extension; //Get file path in wwwroot folder string imageUrl = "\\images\\products\\" + uniqueFileName; //Get absolute path string uploads = Path.Combine(_appHostingEnv.WebRootPath, "images", "products"); string path = Path.Combine(uploads, uniqueFileName); //Upload image on the server await imageWriter.UploadImageAsync(file, path); imageRepository.AddImage(new Image { Name = uniqueFileName, Url = imageUrl, ProductID = productId }); //Add new image in list to return back to client Image image = new Image { Name = uniqueFileName, Url = imageUrl }; images.Add(image); } } return(Ok(images)); }
public ActionResult <String> AddImage(int id) { IFormFile files = Request.Form.Files[0]; Personeel persoon = _personeelRepository.GetBy(id); if (files != null) { MemoryStream ms = new MemoryStream(); files.CopyTo(ms); Image image = new Image { ImageData = ms.ToArray(), Persoon = persoon, PersoonId = persoon.Id }; _imageRepository.AddImage(image); _imageRepository.SaveChanges(); return(Ok()); } return(BadRequest()); }
public void UploadAndLinkImageToClothingItem(string clothingItemId, IFormFileCollection files) { if (string.IsNullOrEmpty(clothingItemId)) { throw new Exception(string.Format(Resources.Error.ImageService_InvalidClothingItemId_Template, clothingItemId)); } if (files.Count > 0) { foreach (var file in files) { var image = new Image { Id = Guid.NewGuid(), Name = file.FileName }; using (var ms = new MemoryStream()) { file.CopyTo(ms); image.ImageFile = ms.ToArray(); } var validationResult = image.Validate(); if (validationResult.IsValid()) { _repository.AddImage(image); } else { throw new ValidationException(validationResult); } _repository.LinkImageToClothingItem(imageId: image.Id, clothingItemId: Guid.Parse(clothingItemId)); } } }
public async Task AddImage(string name, string url) { await _ImageRepository.AddImage(name, url); }