public HttpResponseMessage Post(HttpRequestMessage request) { return(CreateHttpResponse(request, () => { ResponseViewModel rm = new ResponseViewModel(); UploadImageViewModel pf = new UploadImageViewModel(); var httpRequest = HttpContext.Current.Request; HttpResponseMessage response = null; foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var tempimagename = Guid.NewGuid(); var ImageName = tempimagename + ".jpg"; var ThumbnailImageName = tempimagename + "_thumb" + ".jpg"; var ThumbnailImageNameSmaller = tempimagename + "_thumbsmall" + ".jpg"; var FolderPath = "~" + Constants.ImagePath; if (!_ifileUploadService.UploadImageAndThumbnail(postedFile, 500, 400, FolderPath, ImageName, ThumbnailImageName, ThumbnailImageNameSmaller)) { rm.status = 0; response = request.CreateResponse(HttpStatusCode.OK, rm); return response; } // pf.FileName = ImageName; pf.ThumbnailFileName = ThumbnailImageName; pf.FilePath = Constants.ImagePath; rm.responseData = pf; rm.status = 1; rm.message = Constants.uploadSuccess; } response = request.CreateResponse(HttpStatusCode.OK, rm); return response; })); }
public async Task <IActionResult> UploadImage([FromForm] UploadImageViewModel uploadImage, CancellationToken token) { try { ImageFile image = await imageService.UploadImage(uploadImage.Image, uploadImage.ImageDescription, uploadImage.ImageResizeThreshold, token).ConfigureAwait(false); return(Ok(new Dictionary <string, int>() { { "id", image.Id } })); } catch (SixLabors.ImageSharp.UnknownImageFormatException e) { logger.LogError(e, "Error uploading image"); return(StatusCode(StatusCodes.Status400BadRequest, new Dictionary <string, string>() { { "errorMessage", "Invalid image format. Use GIF, PNG, JPEG or BMP" } })); } catch (Exception e) { logger.LogError(e, "Error uploading image"); return(StatusCode(StatusCodes.Status500InternalServerError, new Dictionary <string, string>() { { "errorMessage", e.Message } })); } }
public ActionResult UploadImage_Post(UploadImageViewModel model, bool captchaValid) { ValidateCaptcha(captchaValid); using (var image = ValidateAndExtractImage(model.ImageFile)) { if (!ModelState.IsValid) { return View(model); } try { var jobID = Guid.NewGuid(); var blob = UploadImageToStorage(image, jobID.ToString()); var originalFileName = model.ImageFile.FileName; CreateNewOCRTask(jobID, originalFileName, model.EmailAddress, blob.Name); return View("UploadImageSuccessful"); } catch (Exception e) { Error("An error occurred: " + e.Message); return View(model); } } }
public ActionResult ImageUpload() { UploadImageViewModel imageVM = new UploadImageViewModel(); imageVM.LocalPath = userService.GetUser(User.Identity.GetUserId()).ProfilePicUrl; return(PartialView(imageVM)); }
public async Task <IActionResult> Create(UploadImageViewModel viewAnime) { if (ModelState.IsValid) { if (viewAnime.ImageFile != null) { var fileName = Path.GetFileName(viewAnime.ImageFile.FileName); Path.GetTempFileName(); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", fileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await viewAnime.ImageFile.CopyToAsync(stream); // validate file, then move to CDN or public folder } viewAnime.Anime.ImagePath = viewAnime.ImageFile.FileName; } _context.Add(viewAnime.Anime); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["GenreId"] = new SelectList(_context.Genre, "GenreId", "GenreId", viewAnime.Anime.GenreId); return(View(viewAnime.Anime)); }
public ActionResult UploadImage(int id, UploadImageViewModel requestedViewModel) { if (ModelState.IsValid) { string[] authorziedContentTypes = new string[] { "image/gif", "image/png", "image/jpeg", "image/pjpeg" }; string contentType = getMimeFromFile(requestedViewModel.File); if (!authorziedContentTypes.Any(x => x.Equals(contentType, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError("File", "Du må kun uploade .gif, .png og .jpg"); } if (ModelState.IsValid) { Furniture furniture = FurnitureService.GetById(id); Image image = ImageService.Upload(requestedViewModel.File, furniture); ImageService.Resize(image, FurnitureService.ImageSizes, furniture); if (requestedViewModel.ProfileImage.HasValue && requestedViewModel.ProfileImage.Value) { FurnitureService.SetProfileImage(furniture, image); } return(new RedirectResult(Url.Action("Update", new { id = id }) + "#images")); } } TempData["ModelStateFile"] = ModelState.Where(x => x.Key == "File"); return(new RedirectResult(Url.Action("Update", new { id = id }) + "#images")); }
public ActionResult UploadImage_Post(UploadImageViewModel model, bool captchaValid) { ValidateCaptcha(captchaValid); using (var image = ValidateAndExtractImage(model.ImageFile)) { if (!ModelState.IsValid) { return(View(model)); } try { var jobID = Guid.NewGuid(); var blob = UploadImageToStorage(image, jobID.ToString()); var originalFileName = model.ImageFile.FileName; CreateNewOCRTask(jobID, originalFileName, model.EmailAddress, blob.Name); return(View("UploadImageSuccessful")); } catch (Exception e) { Error("An error occurred: " + e.Message); return(View(model)); } } }
// GET: AlbumPosts/Create public IActionResult Create() { UploadImageViewModel viewalbumpost = new UploadImageViewModel(); viewalbumpost.AlbumPost = new AlbumPost(); ViewData["UserId"] = new SelectList(_context.ApplicationUser, "Id", "Id"); return(View(viewalbumpost)); }
// GET: Anime/Create public IActionResult Create() { UploadImageViewModel viewAnime = new UploadImageViewModel(); viewAnime.Anime = new Anime(); ViewData["GenreId"] = new SelectList(_context.Genre, "GenreId", "Name"); return(View(viewAnime)); }
public ActionResult UploadImage(int id, UploadImageViewModel viewModel) { var path = imgHelper.SaveImage(viewModel.Image); viewModel.Path = path; return(View(viewModel)); }
// GET: IMS/Artwork/Edit/1 public ActionResult UploadImage(int id) { var viewModel = new UploadImageViewModel { ArtworkId = id }; return(View(viewModel)); }
// GET: Products/Create public IActionResult Create() { UploadImageViewModel viewproduct = new UploadImageViewModel(); viewproduct.product = new Product(); ViewData["ProductTypeId"] = new SelectList(_context.ProductType, "ProductTypeId", "Label"); ViewData["UserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id"); return(View(viewproduct)); }
public ActionResult UploadImage(UploadImageViewModel model) { if (!ModelState.IsValid) { return(View("_UploadImage", model)); } var imageFilePath = SaveImage(model.AttachedImage, nameof(UploadImage)); var imageId = _imageService.Create(imageFilePath, model.ImageCategory); return(this.Content("Refresh")); }
public async Task <ActionResult> UploadImage(UploadImageViewModel model) { if (!ModelState.IsValid) { return(View("_UploadImage", model)); } var imageFilePath = SaveImage(model.AttachedImage); await _imageService.CreateAsync(imageFilePath, model.ImageCategory); return(Content("Refresh")); }
public IActionResult Index() { var viewModObj = new UploadImageViewModel(); var listOfCategories = repo.GetCategories().ToList(); viewModObj.Categories = listOfCategories.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }); return(View(viewModObj)); }
public async Task <IActionResult> UploadNewImages(UploadImageViewModel viewModObj, ICollection <IFormFile> images) { if (images.Count() != 0) { foreach (var image in images) { if (Path.GetExtension(image.FileName) != ".jpeg" && Path.GetExtension(image.FileName) != ".jpg" && Path.GetExtension(image.FileName) != ".png") { TempData["FileNotAccepted"] = "File not accepted." + " File must be of type jpg, jpeg or png"; return(RedirectToAction("Index", "Upload")); } else { if (viewModObj.Image.FileName == null) { TempData["InfoName"] = "Please type a folder name"; return(RedirectToAction("Index", "Upload")); } else { await repo.UploadAndSaveAllImages(viewModObj, images); return(RedirectToAction("Index", "Home")); } } } } else { if (viewModObj.Image.FileName != null) { //Implementation in Upload/Index.cshtml TempData["Info"] = "There is no images selected, please choose one or more!"; return(RedirectToAction("Index", "Upload")); } else { TempData["InfoName"] = "Please choose a image and type a folder name where you want to save your photo !"; return(RedirectToAction("Index", "Upload")); } } return(Ok()); }
public ActionResult UploadImage(UploadImageViewModel model) { //Check if all simple data annotations are valid if (ModelState.IsValid) { //Prepare the needed variables Bitmap original = null; var name = "newimagefile"; var errorField = string.Empty; if (model.IsUrl) { errorField = "Url"; name = GetUrlFileName(model.Url); original = GetImageFromUrl(model.Url); } else if (model.File != null) { errorField = "File"; name = Path.GetFileNameWithoutExtension(model.File.FileName); original = Bitmap.FromStream(model.File.InputStream) as Bitmap; } //If we had success so far if (original != null) { var img = CreateImage(original, model.X, model.Y, model.Width, model.Height); var fileName = Guid.NewGuid().ToString(); var oldFilepath = userService.GetUser(User.Identity.GetUserId()).ProfilePicUrl; var oldFile = Server.MapPath(oldFilepath); //Demo purposes only - save image in the file system var fn = Server.MapPath("~/Content/ProfilePics/" + fileName + ".png"); img.Save(fn, System.Drawing.Imaging.ImageFormat.Png); userService.SaveImageURL(User.Identity.GetUserId(), "~/Content/ProfilePics/" + fileName + ".png"); if (System.IO.File.Exists(oldFile)) { System.IO.File.Delete(oldFile); } return(RedirectToAction("UserProfile", new { id = User.Identity.GetUserId() })); } else //Otherwise we add an error and return to the (previous) view with the model data { ModelState.AddModelError(errorField, Resources.UploadError); } } return(View("ImageUpload", model)); }
public void Upload_Image_Post() { var userManager = new UserManager <ApplicationUser>(new TestUserStore()); UploadImageViewModel image = new UploadImageViewModel() { IsFile = true, UserId = "402bd590-fdc7-49ad-9728-40efbfe512ec", LocalPath = "dddd" }; AccountController controller = new AccountController(userService, userProfileService, goalService, updateService, commentService, followRequestService, followUserService, securityTokenService, userManager); ViewResult result = controller.UploadImage(image) as ViewResult; Assert.IsNotNull(result); Assert.IsInstanceOfType(typeof(UploadImageViewModel), result.ViewData.Model, "WrongType"); Assert.AreEqual("ImageUpload", result.ViewName); }
public IActionResult UploadPhoto(UploadImageViewModel image) { if (ModelState.IsValid) { if (!_fileService.IsImage(image.Photo)) { ModelState.AddModelError("", "Uploaded file is not an image >:("); } _fileService.UploadFile(image.Photo); return(View()); } return(View()); }
public async Task <IActionResult> Upload([FromForm] UploadImageViewModel model) { var file = model.File; using var stream = file.OpenReadStream(); var path = this.imageService.ConvertImage(stream); var user = await this.UserServices.FindByIdAsync(this.User.GetId()); var result = await this.UserServices.UploadAvatarImagePath(user, path); if (!result.Succeeded) { return(this.BadRequest(result.Errors)); } return(this.Ok(new { Path = path.NormalizedAPIPath(this.environment.ContentRootPath) })); }
public async Task <IActionResult> UploadBookCoverImage(UploadImageViewModel uploadImageViewModel) { if (ModelState.IsValid) { string path = webHostEnvironment.WebRootPath + appSettings.Value.FileSettings.BookCovers; string imageId = await fileService.WriteImage(uploadImageViewModel.Photo, path); return(Ok(new UploadImageResponseDTO { ImageId = imageId })); } else { return(BadRequest(ModelState)); } }
public async Task <IActionResult> Upload(UploadImageViewModel image, IFormFile File) { if (File != null && ModelState.IsValid) { var user = userManager.GetUserAsync(User).Result; if (image.Description == null) { image.Description = string.Empty; } var img = new SingleImages() { Name = image.Name, Category = image.Category, Description = image.Description, Location = image.Location, User = user, CreatedOn = DateTime.UtcNow.AddHours(3), Rating = 0, }; string path = Path.Combine(environment.WebRootPath, "uploads", user.Id, "images"); Directory.CreateDirectory(Path.Combine(path)); // the FileStream class that will save the image to it's directory using (FileStream fs = new FileStream(Path.Combine(path, File.FileName), FileMode.Create)) { await File.CopyToAsync(fs); } img.Path = user.Id + "/images/" + File.FileName; user.ImagesCount++; db.Update(user); db.SingleImages.Add(img); db.SaveChanges(); return(RedirectToAction("Index", "MyProfile")); } return(View(image)); }
public async Task <IActionResult> UploadImage(UploadImageViewModel viewmodel) { if (viewmodel.File == null || viewmodel.File.Length == 0) { return(Content("file not selected")); } var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot", "images", viewmodel.Filename); using (var stream = new FileStream(path, FileMode.Create)) { await viewmodel.File.CopyToAsync(stream); } return(RedirectToAction("ManagePosts", "Admin", new { changeAction = "uploaded" })); }
public JsonResult UploadPhotos(UploadImageViewModel model) { var file = model.ImageFile; string finalFileName = ""; string currentPath = @"~/UploadedImage/" + Session["CurrentUserID"].ToString() + "/"; if (file != null) { if (!Directory.Exists(currentPath)) { Directory.CreateDirectory(Server.MapPath(currentPath)); } file.SaveAs(Server.MapPath(currentPath + "/" + file.FileName)); string str = "/UploadedImage/" + Session["CurrentUserID"].ToString() + "/" + file.FileName; finalFileName = "<div class='thumbnail border-2 ml - 2'>" + "<img src='" + str + "' class='img-thumbnail' height='150' width='150'/>" + "</div>"; } return(Json(finalFileName, JsonRequestBehavior.AllowGet)); }
private async void ImageList_Drop(object sender, DragEventArgs e) { if (e.DataView.Contains(StandardDataFormats.StorageItems)) { var items = await e.DataView.GetStorageItemsAsync(); foreach (var i in items) { if (i is Windows.Storage.StorageFile f) { string ext = f.Name.Substring(f.Name.LastIndexOf('.') + 1); switch (ext) { case "jpg": case "jpeg": case "png": case "gif": case "tif": case "tiff": UploadImageViewModel imageVm = await UploadImageViewModel.CreateFromStreamAsync(await f.OpenStreamForReadAsync()); ViewModel.AddImage(imageVm); break; default: // TODO: Alert user break; } } } } else if (e.DataView.Contains(StandardDataFormats.Bitmap)) { var item = await e.DataView.GetBitmapAsync(); if (item != null) { UploadImageViewModel imageVm = await UploadImageViewModel.CreateFromStreamAsync((await item.OpenReadAsync()).AsStreamForRead()); ViewModel.AddImage(imageVm); } } }
public async Task <IActionResult> UploadImage(UploadImageViewModel model) { if (ModelState.IsValid) { var size = model.Files.Sum(e => e.Length); if (size > 5242880) { ModelState.AddModelError(string.Empty, "File Size is not greater than 5MB"); return(View(model)); } var array = await UploadImages(model.Files); return(View()); } return(View(model)); }
public async Task <IActionResult> Create(UploadImageViewModel viewalbumpost) { // add current dateTime viewalbumpost.AlbumPost.DatePosted = DateTime.Now; ModelState.Remove("AlbumPost.UserId"); // adding current userId var user = await GetCurrentUserAsync(); viewalbumpost.AlbumPost.UserId = user.Id; if (ModelState.IsValid) { if (viewalbumpost.ImageFile != null) { // don't rely on or trust the FileName property without validation //**Warning**: The following code uses `GetTempFileName`, which throws // an `IOException` if more than 65535 files are created without // deleting previous temporary files. A real app should either delete // temporary files or use `GetTempPath` and `GetRandomFileName` // to create temporary file names. var fileName = Path.GetFileName(viewalbumpost.ImageFile.FileName); Path.GetTempFileName(); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", fileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await viewalbumpost.ImageFile.CopyToAsync(stream); // validate file, then move to CDN or public folder } viewalbumpost.AlbumPost.ImagePath = viewalbumpost.ImageFile.FileName; } _context.Add(viewalbumpost.AlbumPost); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["UserId"] = new SelectList(_context.ApplicationUser, "Id", "Id", viewalbumpost.AlbumPost.UserId); return(View(viewalbumpost.AlbumPost)); }
public async Task <IActionResult> UploadNewImage(UploadImageViewModel image) { if (image.ImageUpload != null) { string path = "/images/" + image.ImageUpload.FileName; using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create)) { await image.ImageUpload.CopyToAsync(fileStream); } ImageModel galleryImage = new ImageModel() { Url = path }; _context.Images.Add(galleryImage); _context.SaveChanges(); } return(RedirectToAction("Index", "Gallery")); }
public UploadImageViewModel UploadImage(UploadImageInputModel data, string virtualPath) { UploadImageViewModel result; if (data.name == null) { data.name = Guid.NewGuid(); } var fileExtension = "png"; var file = data.base64; if (file.Contains("data:")) { try { data.base64 = file.Split(",")[1]; fileExtension = file.Split(",")[0].Split(";")[0].Split("/")[1]; } catch (Exception) { } } byte[] bytes = Convert.FromBase64String(data.base64); var filename = data.name + "." + fileExtension; var fullPath = Path.Combine(pathToSave, filename); if (bytes.Length > 0) { using (var stream = new FileStream(fullPath, FileMode.Create)) { stream.Write(bytes, 0, bytes.Length); stream.Flush(); } } result = new UploadImageViewModel(virtualPath, filename, fileExtension); return(result); }
public IActionResult UploadImage() { string path = Path.Combine(Directory.GetCurrentDirectory(), $"wwwroot/images/"); var imageList = Directory.GetFiles(path); List <UploadImageViewModel> uploadedImages = new List <UploadImageViewModel>(); foreach (var image in imageList) { FileInfo fileInfo = new FileInfo(image); UploadImageViewModel model = new UploadImageViewModel(); model.FullName = image.Substring(image.IndexOf("wwwroot")).Replace("wwwroot/", string.Empty); model.FileName = fileInfo.Name; model.Size = fileInfo.Length / 1024; uploadedImages.Add(model); } return(View(uploadedImages)); }
public ActionResult UploadImage() { var model = new UploadImageViewModel(); return(PartialView("_UploadImage", model)); }
public ActionResult UploadImage_Get(UploadImageViewModel model) { return View(model); }