public IActionResult Create([Bind("Id,Title,TagStr,Photo")] PhotoCreateViewModel model) { if (ModelState.IsValid) { var uniqueFileName = ProcessUploadedFile(model); #region Add Photo var newPhoto = new Photo { Title = model.Title, PhotoPath = uniqueFileName }; photoService.Add(newPhoto); #endregion var tags = model.TagStr.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList(); foreach (var tag in tags) { var newTag = new Tag { Name = tag, PhotoId = newPhoto.Id }; tagService.Add(newTag); } return(RedirectToAction("Details", new { id = newPhoto.Id })); } return(View()); }
public async Task <HttpResponseMessage> Add() { try { var provider = new CustomMultipartFormDataStreamProvider(workingFolder); await Task.Run(async() => await Request.Content.ReadAsMultipartAsync(provider)); var photoDto = new PhotoDto(); foreach (var file in provider.FileData) { var data = provider.FormData; var fileInfo = new FileInfo(file.LocalFileName); photoDto = new PhotoDto { Name = fileInfo.Name, PhotographerId = int.Parse(data.Get("Content[PhotographerId]")) }; photoService.Add(photoDto); } return(new HttpResponseMessage(HttpStatusCode.OK)); } catch (Exception ex) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } }
public IActionResult Create(Photo photo) { if (ModelState.IsValid) { _photoService.Add(photo); return(RedirectToAction("Index")); } return(View(photo)); }
// POST: api/Photos public IHttpActionResult PostPhoto(PhotoViewModel photoViewModel) { var photo = new Photo(); Mapper.Map(photoViewModel, photo); photo.User = _userManager.FindByName(RequestContext.Principal.Identity.Name); photo = _photoService.Add(photo); photoViewModel.Id = photo.Id; return(Created(Url.Link("DefaultApi", new { controller = "Photos", id = photoViewModel.Id }), photoViewModel)); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _datingService.GetUser(userId); var file = photoForCreationDto.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } } photoForCreationDto.Url = uploadResult.Url.ToString(); photoForCreationDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map <Photo>(photoForCreationDto); photo.UserId = userId; photo.User = userFromRepo; if (!userFromRepo.Photos.Any(u => u.IsMain)) { photo.IsMain = true; } try { _photoService.Add(photo); var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo); return(StatusCode(201)); } catch { return(BadRequest("Could not add the photo")); } }
public async Task <IActionResult> Create(ProductViewModel model) { if (ModelState.IsValid) { var product = _mapper.Map <Product>(model); if (model.Description != null) { product.Description = (model.Description); } await _productService.Add(product); if (model.UploadedPhotos != null) { foreach (var photo in model.UploadedPhotos) { product.Photos.Add(await _photoService.Add(photo, product.Id, _webHostEnvironment.WebRootPath)); } } } return(RedirectToAction("Index")); }
private Photo SavePhoto() { if (Memory == null) { return(null); } try { return(_photoService.Add(Photo)); } catch (Exception e) { return(null); } }
public ActionResult Create(CreatePhotoModel model, HttpPostedFileBase file) { var userId = User.Identity.GetUserId(); if (userId == null) { return(RedirectToAction("GetAll")); } if (ModelState.IsValid) { // check image size if (Request.Files.Count > 0) { file = Request.Files[0]; if (file != null && file.ContentLength > 0) { if (file.ContentLength <= 1048576) { var photo = Mapper.Map <CreatePhotoModel, Photo>(model); photo.UserId = userId; var status = _service.Add(photo, file); if (string.IsNullOrWhiteSpace(status.ErrorMessage)) { return(RedirectToAction("UserPhotos")); } else { ModelState.AddModelError("IsAnImage", status.ErrorMessage); } } else { ModelState.AddModelError("Size", "Current image takes more than 1 MB"); } } else { ModelState.AddModelError("Empty", "Current image isn’t exist"); } } } var errors = ViewData.ModelState.Where(n => n.Value.Errors.Count > 0).ToList(); return(View(model)); }
public ActionResult Create(DetailPhotoViewModel pic, HttpPostedFileBase uploadImage) { if (ModelState.IsValid && uploadImage != null && uploadImage.ContentLength <= 2000000 && uploadImage.ContentType.Contains("image")) { string fileName = System.IO.Path.GetFileName(uploadImage.FileName); uploadImage.SaveAs(Server.MapPath("~/Files/" + fileName)); PhotoDTO photo = new PhotoDTO { Description = pic.Description, Name = fileName, UploadTime = DateTime.Now, Path = "/Files/" + fileName, AuthorId = User.Identity.GetUserId() }; photoService.Add(photo); return(RedirectToAction("Index")); } return(View("Error")); }
public IActionResult Add(AddPhotoViewModel viewModel) { if (!ModelState.IsValid) { return(BadRequest("Photo properties are not valid.")); } if (!IsCurrentUser(viewModel.UserId)) { return(BadRequest("User credentials are not valid.")); } var photo = GetMappedPhoto(viewModel); _photoService.Add(photo); return(Ok(viewModel.AlbumId)); }
public IActionResult Post([FromForm] PhotoForAddDto photoForAddDto) { if (photoForAddDto.File.Length > 0) { ImageUploadResult imageUploadResult = _photoUpload.ImageUpload(photoForAddDto.File); var mapResult = _mapper.Map <Photo>(photoForAddDto); mapResult.PhotoUrl = imageUploadResult.Uri.ToString(); mapResult.PublicId = imageUploadResult.PublicId; mapResult.UserId = User.Claims.GetUserId().Data; IResult result = _photoService.Add(mapResult); if (result.IsSuccessful) { this.RemoveCache(); return(Ok(result.Message)); } return(this.ServerError(result.Message)); } return(BadRequest()); }
public IActionResult AdvertAdd(Advert advert) { advert.ListingDate = DateTime.Now; var advertAdd = _advertService.Add(advert); if (ModelState.IsValid) { var filePath = Path.Combine(_hostEnvironment.WebRootPath, "resimler"); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } foreach (var item in advert.Files) { using (var fileStream = new FileStream(Path.Combine(filePath, item.FileName), FileMode.Create)) { item.CopyTo(fileStream); } advert.Photos.Add(new Photo { FileName = item.FileName, AdvertId = advert.Id }); } foreach (var photo in advert.Photos) { _photoService.Add(photo); } TempData["SuccessMessage"] = advertAdd.Message; return(RedirectToAction("AdvertList", "RealEstate")); } return(View()); }
//[Route("add")] public ActionResult Add(int contentId) { var files = Request.Form.Files; var photo = new Photo(); photo.ContentId = contentId; long size = files.Sum(f => f.Length); //var path = Path.GetTempFileName(); foreach (var file in files) { if (file.Length > 0) { var path = Path.Combine(AppContext.BaseDirectory, "Images", file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { file.CopyTo(stream); } } photo.Path = "images/" + file.FileName; var images = _photoService.GetByContent(contentId); if (!images.Any(p => p.IsMain)) { photo.IsMain = true; } _photoService.Add(photo); } return(Ok(new { count = files.Count, size })); }
public IActionResult Post([FromBody] Photo photo) { _photoService.Add(photo); return(Ok()); }
public ActionResult UploadPhoto(UploadPhotoViewModel photo) { photoService.Add(photo.ToBllPhoto(accountService.GetUserByLogin(User.Identity.Name).Id)); return(RedirectToAction("Index", "Profile")); }
public ActionResult AddPhoto(HttpPostedFileBase file) { var fileName = string.Empty; var path = string.Empty; var thumbFileName = string.Empty; var thumbFilePath = string.Empty; //check exist file from from if (file != null) { var fileSize = file.ContentLength; //check file size //max image size int maxImageSize = int.Parse(ConfigurationManager.AppSettings["MaxByteImageSize"]); if (fileSize > maxImageSize * 1024) { TempData["Message"] = "file is too big"; return(RedirectToAction("UserGallery", "Gallery")); } var fileExtention = Path.GetExtension(file.FileName).ToLower(); //valid exeptions string[] listOfExtensions = ConfigurationManager.AppSettings["ValidImageExtensions"].Split(','); var isAccept = false; //check valid file extension foreach (var item in listOfExtensions) { if (fileExtention == item) { isAccept = true; break; } } if (!isAccept) { TempData["Message"] = "File isn't a picture"; return(RedirectToAction("UserGallery")); } fileName = Path.GetFileName(file.FileName); //upload path from app.settings var uploadPath = ConfigurationManager.AppSettings["UploadImagePath"]; var dirPath = Path.Combine(Server.MapPath(uploadPath), User.Identity.GetUserId()); path = Path.Combine(dirPath, fileName); //check exist directory if (Directory.Exists(dirPath)) { if (System.IO.File.Exists(path)) { TempData["Message"] = "The file with same name ia already exist"; return(RedirectToAction("UserGallery")); } else { file.SaveAs(path); } } else { Directory.CreateDirectory(dirPath); file.SaveAs(path); } //creates thumbnail Rectangle cropRectangle = new Rectangle(0, 0, 420, 236); Bitmap src = Image.FromStream(file.InputStream, true, true) as Bitmap; Bitmap target = new Bitmap(cropRectangle.Width, cropRectangle.Height); target.SetResolution(src.HorizontalResolution, src.VerticalResolution); using (Graphics g = Graphics.FromImage(target)) { g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY); g.DrawImage(src, cropRectangle, 0, 0, src.Width, src.Height, GraphicsUnit.Pixel, wrapMode); } } //thumbnail file name thumbFileName = Path.GetFileNameWithoutExtension(file.FileName) + "_thumb"; thumbFileName += Path.GetExtension(file.FileName); //thumbnail path var thumbPath = Path.Combine(Server.MapPath(uploadPath + User.Identity.GetUserId()), "thumbnail"); thumbFilePath = Path.Combine(thumbPath, thumbFileName); //check exist directory if (Directory.Exists(thumbPath)) { if (!System.IO.File.Exists(thumbFilePath)) { target.Save(thumbFilePath, System.Drawing.Imaging.ImageFormat.Jpeg); } } else { Directory.CreateDirectory(thumbPath); target.Save(thumbFilePath, System.Drawing.Imaging.ImageFormat.Jpeg); } } var userId = _userService.FindUserByName(User.Identity.Name).Result.Id; var pic = new PhotoDto() { Id = Guid.NewGuid().ToString(), PhotoName = fileName, DateTimeUploading = DateTime.Now, PhotoPath = path, ThumbnailPath = thumbFilePath, IsPublish = false, ApplicationUserId = userId }; _photoService.Add(pic); ViewBag.StatusMessage = "File successfully uploaded!"; return(RedirectToAction("GetAllPath", "Gallery", new { userId = pic.ApplicationUserId })); }