public async Task <ProcessResult <Post> > SaveUploadImagesAsync(Guid postKey, ICollection <IFormFile> files) { var processResult = _repository.GetPostByKey(postKey); if (!processResult.IsOk) { return(processResult); } var post = processResult.Data; var postImages = new List <PostImage>(); foreach (var file in files) { var postImage = new PostImage { Extension = Path.GetExtension(file.FileName) }.EnsureValidKey(); var filePath = GetPostImagePath(postImage.FilePath); using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { await file.CopyToAsync(fileStream); } var thumbPath = Path.Combine(_uploadImageRootPath, postImage.ThumbPath); await _imageProcessService.ResizeByHeightAsync(filePath, thumbPath, _settings.ThumbHeight); postImages.Add(postImage); } post.WithPostImages(postImages); processResult = _repository.UpsertPost(post); return(processResult); }
public ActionResult Create([Bind(Include = "PostImageID,Image,ImagePath")] PostImage postImage, HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { postImage.ImagePath = Path.GetExtension(file.FileName); postImage.Image = ConvertToBytes(file); } int number = 0; var num = db.PostImages.ToList(); foreach (var n in num) { number++; } if (number == 0) { postImage.PostImageID = 0; } else { postImage.PostImageID = number; } if (ModelState.IsValid) { db.PostImages.Add(postImage); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(postImage)); }
public IActionResult Upload(IFormFile[] file, Guid?id) //bilinçli olarak file býrakýldý. dropzone içerinde tanýmlý kelime file!!!! { if (!id.HasValue) { Post post = _postRepository.GetById(id.Value); if (id == null) { return(NotFound()); } if (file.Length > 0) { foreach (var item in file) { var result = _fileUpload.Upload(item); if (result.FileResult == Utility.FileResult.Succeded) { PostImage image = new PostImage(); image.ImageURL = result.FileUrl; image.PostId = id.Value; } } } } return(View()); }
public async Task <PostImage> AddPostImage(IFormFile file, int postId) { var post = await postRepository.Get(postId); if (file == null) { return(null); } if (file.Length == 0) { return(null); } var imagePath = Path.Combine(webHostEnvironment.WebRootPath, "images", file.FileName); var imageReader = file.OpenReadStream(); using (var fileStream = new FileStream(imagePath, FileMode.Create)) { imageReader.CopyTo(fileStream); var postImage = new PostImage { Source = fileStream.Name, Post = post }; await ctx.PostImages.AddAsync(postImage); return(postImage); } }
public async Task <IActionResult> Edit(Guid id, [Bind("ImageURL,Base64,Active,PostId,Id,CreatedComputerName,CreatedDate,CreatedBy,CreatedIp")] PostImage postImage) { if (id != postImage.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(postImage); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PostImageExists(postImage.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["PostId"] = new SelectList(_context.Posts, "Id", "Content", postImage.PostId); return(View(postImage)); }
public ImageDto Find(int id) { PostImage postImage = _repository.Find(id); ImageDto imageDto = _mapper.Map <ImageDto>(postImage); return(imageDto); }
public int Delete(int id) { PostImage p = this.context.PostImages.SingleOrDefault(pp => pp.Id == id); this.context.PostImages.Remove(p); return(this.context.SaveChanges()); }
public IActionResult Upload(IFormFile[] file, Guid?id) //Dropzone içerisinde tanımlı kelıme file { if (id.HasValue) { Post post = _postRepository.GetById(id.Value); if (post == null) { return(NotFound()); } if (file.Length > 0) { foreach (var item in file) { var result = _fileUpload.Upload(item); if (result.FileResult == Utility.FileResult.Succeded) { PostImage image = new PostImage { ImageUrl = result.FileUrl, PostId = id.Value }; _postImageRepository.Add(image); _postImageRepository.Save(); } } } } return(View()); }
public ActionResult ValidateImages(int id) { var postImage = db.PostImages.Find(id); SaveImage save = new SaveImage(); int number = 0; var num = db.SaveImages.ToList(); foreach (var n in num) { number++; } if (number == 0) { save.SaveImageID = 0; } else { save.SaveImageID = number; } save.Image = postImage.Image; save.ImagePath = postImage.ImagePath; db.SaveImages.Add(save); db.SaveChanges(); PostImage c = db.PostImages.Find(postImage.PostImageID); db.PostImages.Remove(c); db.SaveChanges(); return(RedirectToAction("AdminViewIndex", "PostImages")); }
public JsonResult DeleteFile(string id) { if (String.IsNullOrEmpty(id)) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(new { Result = "Error" })); } try { Guid guid = new Guid(id); PostImage postImage = db.PostImages.Find(guid); if (postImage == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return(Json(new { Result = "Error" })); } //Remove from database db.PostImages.Remove(postImage); db.SaveChanges(); //Delete file from the file system var path = Path.Combine(Server.MapPath("~/App_Data/Upload/"), postImage.Id + postImage.Extension); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } return(Json(new { Result = "OK" })); } catch (Exception ex) { return(Json(new { Result = "ERROR", Message = ex.Message })); } }
public int Update(PostImage image) { PostImage p = this.context.PostImages.SingleOrDefault(pp => pp.Id == image.Id); p.ImgPath = image.ImgPath; return(this.context.SaveChanges()); }
public PostImage GetPostImage(ISession session) { PostImage ei = (Id != 0) ? (PostImage)session.Load(typeof(PostImage), Id) : new PostImage(); ei.Image = (Image)session.Load(typeof(Image), Image.Id); ei.Post = (Post)session.Load(typeof(Post), Post.Id); return(ei); }
public JsonResult AddImage([FromBody] PostImage image) { var currentUserId = User.Claims.SingleOrDefault(a => a.Type == "UserId").Value; var host = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}"; var path = serviceOfPost.AddImage(host, currentUserId, image); return(Json(path)); }
public async Task <PostImage> Create(PostImage image) { var img = await context.PostImages.AddAsync(image); await context.SaveChangesAsync(); return(img.Entity); }
public ActionResult DeleteConfirmed(int id) { PostImage postImage = db.PostImages.Find(id); db.PostImages.Remove(postImage); db.SaveChanges(); return(RedirectToAction("Index")); }
public JsonResult addPost(string text, string image, List <string> images, string video) { string Message; int code; if (Session["ApplicationUser"] != null) { if ((text != "" || images.Count != 0 || video != "") && text.Length <= 500) { var User = (Models.User)Session["ApplicationUser"]; Post currentPost = new Post(); //if (image != "" && image.Length>=50) //{ // byte[] contents = convertIntoByte(image); // string subpath = "~/images/userPosts/"; // string fileName = User.UserID + "_Post_" + Guid.NewGuid() + ".jpg"; // var uploadPath = HttpContext.Server.MapPath(subpath); // var path = Path.Combine(uploadPath, Path.GetFileName(fileName)); // System.IO.File.WriteAllBytes(path, contents); // currentPost.imageURL = "/images/userPosts/" + fileName; //} currentPost.UserID = User.UserID; currentPost.text = text; currentPost.postTime = DateTime.UtcNow; currentPost.updateTime = DateTime.UtcNow; db.Post.Add(currentPost); db.SaveChanges(); PostImage currentImage = new PostImage(); if (images != null) { for (int i = 0; i < images.Count; i++) { currentImage.PostID = currentPost.PostID; currentImage.imagePath = images[i]; db.PostImage.Add(currentImage); db.SaveChanges(); } } code = 200; Message = "Post Successfully added"; return(Json(new { code, Message }, JsonRequestBehavior.AllowGet)); } else { code = 400; Message = "UnAuthorized Changing"; return(Json(new { code, Message }, JsonRequestBehavior.AllowGet)); } } else { code = 401; Message = "Login First"; return(Json(new { code, Message }, JsonRequestBehavior.AllowGet)); } }
public async Task <IActionResult> Upload(IFormFile file) { if (file == null) { return(BadRequest("File is null")); } if (file.Length == 0) { return(BadRequest("File is empty")); } if (file.Length > 10 * 1024 * 1024) { return(BadRequest("File size cannot exceed 10M")); } var acceptTypes = new[] { ".jpg", ".jpeg", ".png" }; if (acceptTypes.All(t => t != Path.GetExtension(file.FileName).ToLower())) { return(BadRequest("File type not valid, only jpg and png are acceptable.")); } if (string.IsNullOrWhiteSpace(_hostingEnvironment.WebRootPath)) { _hostingEnvironment.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"); } var uploadsFolderPath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads"); if (!Directory.Exists(uploadsFolderPath)) { Directory.CreateDirectory(uploadsFolderPath); } var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName); var filePath = Path.Combine(uploadsFolderPath, fileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } var postImage = new PostImage { FileName = fileName }; _postImageRepository.Add(postImage); await _unitOfWork.SaveAsync(); var result = _mapper.Map <PostImage, PostImageResource>(postImage); return(Ok(result)); }
public async Task <PostImage> AddBlogImage(PostImage postImage) { var result = await _appDbContext.BlogImages.AddAsync(postImage); await _appDbContext.SaveChangesAsync(); postImage = result.Entity; return(postImage); }
public ImageDto Update(ImageDto image) { PostImage postImage = _mapper.Map <PostImage>(image); _repository.Update(postImage); _dal.Save(); return(_mapper.Map <ImageDto>(postImage)); }
public async Task <IActionResult> Upload(IFormFile file) { if (file == null) { return(BadRequest("文件为空")); } if (file.Length == 0) { return(BadRequest("文件大小为0")); } if (file.Length > 10 * 1024 * 1024) { return(BadRequest("文件不能超过10M")); } var acceptTypes = new[] { ".jpg", ".jpeg", ".png" }; if (acceptTypes.All(t => t != Path.GetExtension(file.FileName).ToLower())) { return(BadRequest("文件格式不支持,只支持.jpg .jpeg .png格式的文件")); } if (string.IsNullOrWhiteSpace(hostingEnvironment.WebRootPath)) { hostingEnvironment.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"); } var uploadsFolderPath = Path.Combine(hostingEnvironment.WebRootPath, "uploads"); if (!Directory.Exists(uploadsFolderPath)) { Directory.CreateDirectory(uploadsFolderPath); } var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName); var filePath = Path.Combine(uploadsFolderPath, fileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } var postImage = new PostImage { FileName = fileName }; postImageRepository.Add(postImage); await unitOfWork.SaveAsync(); var result = mapper.Map <PostImage, PostImageResource>(postImage); return(Ok(result)); }
public async Task AddImageToPostShouldWork() { var options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(databaseName: "AddImageToPostShouldWork").Options; var dbContext = new ApplicationDbContext(options); var postsRepo = new EfDeletableEntityRepository <Post>(dbContext); var makesRepo = new EfDeletableEntityRepository <Make>(dbContext); var makesService = new MakesService(makesRepo); var postsService = new PostsService(postsRepo, makesService); var post = new Post() { Id = 1, Name = "random name", Price = 53222, Currency = Currency.LV, Mileage = 25123, Color = new Color(), EngineType = EngineType.Disel, Horsepower = 255, TransmissionType = TransmissionType.Automatic, ManufactureDate = DateTime.Now, Category = new Category(), City = new City(), User = new ApplicationUser(), PhoneNumber = "0897456321", Description = "random descr", Eurostandard = Eurostandard.Five, Condition = Condition.New, VehicleCategory = new VehicleCategory(), }; var image = new Image() { Url = "random", }; await dbContext.Images.AddAsync(image); await dbContext.Posts.AddAsync(post); await dbContext.SaveChangesAsync(); var postImage = new PostImage() { Image = image, ImageId = image.Id, Post = post, PostId = post.Id, }; await postsService.AddImageToPost(1, postImage); Assert.Single(post.Images); }
public string AddImage(string host, string applicationUserCurrent, PostImage image) { var result = serviceOfImage.LoadImage(host, applicationUserCurrent, image); repositoryOfImage.Create(new ImageEntity() { Path = result, PostId = image.PostId }); return(result); }
public void Post(PostImage post) { GameObject postInstance = SpawnPost(imagePostPrototype); postInstance.transform.SetSiblingIndex(0); postInstance.transform.Find("ProfilePic").GetComponent <Image>().sprite = post.Author.ProfilePic; postInstance.transform.Find("Name").GetComponent <Text>().text = post.Author.name; postInstance.transform.Find("Message").GetComponent <Text>().text = post.Text; postInstance.transform.Find("Image").GetComponent <Image>().sprite = post.Image; }
// // GET: /PostImage/Details/5 public ActionResult Details(int id = 0) { PostImage postimage = db.PostImages.Find(id); if (postimage == null) { return(HttpNotFound()); } return(View(postimage)); }
public ImageDto Create(ImageDto image) { PostImage postImage = _mapper.Map <PostImage>(image); PostImage createdPostImage = _repository.Create(postImage); _dal.Save(); ImageDto imageDto = _mapper.Map <ImageDto>(createdPostImage); return(imageDto); }
public PostImage Remove(int id) { PostImage img = _context.PostImages.Find(id); if (img != null) { img = _context.PostImages.Remove(img); } return(img); }
public void AddImageToPost(string postid, string Imagename) { List<int> numlist = new List<int>(); int num = 1; var check = _context.PostImages.Where(x => x.PostId == postid && x.Imagename == Imagename).Any(); var image = new PostImage { Id = num, PostId = postid, Imagename = Imagename }; _context.PostImages.Add(image); Save(); }
public ActionResult Insert(Post item, List <HttpPostedFileBase> fluResim) { { ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", item.CategoryID); try { using (TransactionScope ts = new TransactionScope()) { item.UserID = Convert.ToInt32(Session["id"]); item.PublishDate = DateTime.Now; item.IsDeleted = false; if (ModelState.IsValid) { db.Posts.Add(item); bool sonuc = db.SaveChanges() > 0; if (sonuc) { foreach (HttpPostedFileBase img in fluResim) { PostImage pi = new PostImage(); pi.PostID = item.PostID; bool yuklemeSonucu; string path = FxFonksiyon.ImageUpload(img, "posts", out yuklemeSonucu); if (yuklemeSonucu) { pi.ImagePath = path; } db.PostImages.Add(pi); db.SaveChanges(); } ts.Complete(); TempData["Message"] = FxFonksiyon.GetInformation(MessageFormat.OK); return(RedirectToAction("Index", "Post")); } else { TempData["Message"] = FxFonksiyon.GetInformation(MessageFormat.Err); } } else { TempData["Message"] = FxFonksiyon.GetInformation(MessageFormat.Val); } } } catch (Exception) { TempData["Message"] = FxFonksiyon.GetInformation(MessageFormat.Err); } return(View()); } }
/// <summary> /// Deletes a specific image from the database /// </summary> /// <param name="imageId">The Id of the image to be deleted</param> /// <returns>Nothing</returns> public async Task Delete(int imageId) { await DeleteImageFromPostToImageTable(imageId); PostImage imageToBeDeleted = await _context.PostImages.FindAsync(imageId); await _cloudImage.DeleteAnImageFromCloudStorage(imageToBeDeleted.CloudStorageKey); _context.Entry(imageToBeDeleted).State = EntityState.Deleted; await _context.SaveChangesAsync(); }
public ActionResult Edit(PostImage postimage) { if (ModelState.IsValid) { db.Entry(postimage).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.PostID = new SelectList(db.Posts, "PostID", "Title", postimage.PostID); return(View(postimage)); }
// // GET: /PostImage/Edit/5 public ActionResult Edit(int id = 0) { PostImage postimage = db.PostImages.Find(id); if (postimage == null) { return(HttpNotFound()); } ViewBag.PostID = new SelectList(db.Posts, "PostID", "Title", postimage.PostID); return(View(postimage)); }
/// <summary> /// Конструктор. /// </summary> /// <param name="thumbnail">Данные изображения.</param> /// <param name="bindToPageLifetime">Привязать к времени жизни страницы.</param> public ThumbnailImageSourceViewModel(PostImage thumbnail, bool bindToPageLifetime = true) : base(bindToPageLifetime) { if (thumbnail == null) throw new ArgumentNullException(nameof(thumbnail)); this.thumbnail = thumbnail; }
public ActionResult AddImageToPost(string postid, string slug, string Imagename,PostViewModel p,PostImage i) { if (Request.Files.Count > 0) { var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { i.Imagename = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/BlogImages/PostImages"), i.Imagename); file.SaveAs(path); } } CreatePostViewModel(slug); _blogRepository.AddImageToPost(postid, i.Imagename); return RedirectToAction("EditPost", new { slug = slug }); }