public async Task FileAllowedExtensionsAttributeShuldReturnTrueIfFileExtensionIsInAllowed() { IFormFile file = new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("dummy image")), 0, 10, "Data", "fake.jpg"); var result = await FormFileExtensions.GetBytesAsync(file); Assert.NotEmpty(result); Assert.Equal(10, result.Length); }
public IActionResult PriceList() { var rawHtml = FormFileExtensions.ReadTxtFile(PriceListPagePath); return(View(new RawHtmlViewModel { Html = rawHtml })); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { IFormFile image = value as IFormFile; if (image != null) { if (!FormFileExtensions.IsImage(image)) { return(new ValidationResult(_errorMsg)); } } return(ValidationResult.Success); }
public async Task <ActionResult <Anime> > CrearAnime([FromForm] AnimeCrearViewModel anime) { Anime nuevo = new Anime() { Descripcion = anime.Descripcion, Nombre = anime.Nombre, Numero_episodios = anime.Numero_episodios, Fecha_publicacion = anime.Fecha_publicacion, Fecha_subida = DateTime.UtcNow }; await AniadirGeneros(nuevo, anime.GenerosActivos.Where(ga => ga.Activo).Select(ga => ga.Genero).ToList()); if (anime.Portada != null) { if (FormFileExtensions.IsImage(anime.Portada)) { MemoryStream ms = new MemoryStream(); anime.Portada.CopyTo(ms); nuevo.Portada = ms.ToArray(); } } else { nuevo.Portada = System.IO.File.ReadAllBytes("./wwwroot/14671207_791293424306921_4080708202123646799_n.jpg"); } try { _context.Animes.Add(nuevo); await _context.SaveChangesAsync(); return(StatusCode(StatusCodes.Status201Created, new ApiResponseFormat() { Estado = StatusCodes.Status201Created, Mensaje = $"Anime {nuevo.Nombre} creado exitosamente", Dato = nuevo })); } catch (Exception ex) { return(BadRequest(new ApiResponseFormat() { Estado = StatusCodes.Status406NotAcceptable, Mensaje = ex.Message, Dato = ex.InnerException })); } }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { ICollection <IFormFile> images = value as ICollection <IFormFile>; if (images != null && images.Any()) { foreach (var img in images) { if (!FormFileExtensions.IsImage(img)) { return(new ValidationResult(_errorMsg)); } } } return(ValidationResult.Success); }
public IActionResult UploadImage(IFormFile file) { string wwwrootPath = _hosting.WebRootPath; // Generate a new ID for the image and append it's filetype at the end string imageFilename = $"{Guid.NewGuid()}.{file.ContentType.Substring(file.ContentType.LastIndexOf("/") + 1)}"; string absolutePath = Path.Combine($"{wwwrootPath}/images/{imageFilename}"); // Check if the received file is an image, otherwise do nothing if (!FormFileExtensions.IsImage(file)) { return(BadRequest()); // The sent file is not an image } using (var fileStream = new FileStream(absolutePath, FileMode.Create)){ file.CopyTo(fileStream); } return(Content(imageFilename)); }
public static ValidationResult ValidateFile(object value, ValidationContext context) { ValidationResult result = null; var image = (Image)context.ObjectInstance; if (image.ImageFile == null && image.Id > 0) { return(result); } if (image.ImageFile == null) { result = new ValidationResult($"{context.DisplayName} jest wymagany."); } else if (!FormFileExtensions.IsImage(image.ImageFile)) { result = new ValidationResult($"Wybrany plik nie jest obrazem."); } return(result); }
public async Task <IActionResult> AddEdit(AddEditViewModel model) { var user = await _userManager.GetUserAsync(User); if (ModelState.IsValid && user != null) { Poster file = new Poster(); byte[] imageData = null; if (model?.Poster != null) { imageData = FormFileExtensions.GetImageByteArr(model.Poster); if (FormFileExtensions.ValidateImageSize(model.Poster, _fileSize)) { ModelState.AddModelError("Poster", $"Размер файла не должен превышать {_fileSize} МБ."); return(View(model)); } if (FormFileExtensions.ValidateImageExtension(model.Poster)) { ModelState.AddModelError("Poster", $"Неправильный тип файла."); return(View(model)); } if (FormFileExtensions.ValidatePictureData(model.Poster)) { ModelState.AddModelError("Poster", $"Не получается прочитать файл."); return(View(model)); } string path = "/Files/" + Guid.NewGuid() + model.Poster.FileName; using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create)) { await model.Poster.CopyToAsync(fileStream); } file.Name = model.Poster.FileName; file.Path = path; } else { string name = "NotFound.jpeg"; string path = $"{_appEnvironment.WebRootPath}/Files/{name}"; if (System.IO.File.Exists(path)) { file.Name = name; file.Path = $"/Files/{name}"; } else { file.Name = string.Empty; file.Path = string.Empty; } } if (model.IsEdit) { var movie = _db.Movies.Include(x => x.Poster).FirstOrDefault(x => x.Id == model.Id); if (movie is null) { return(BadRequest()); } else if (movie.User.Id == user.Id) { movie.Name = model.Name; movie.Description = model.Description; movie.YearOfIssue = model.YearOfIssue; movie.Director = model.Director; movie.User = user; if (!string.IsNullOrEmpty(file.Name) && file.Name != "NotFound.jpeg") { if (System.IO.File.Exists(_appEnvironment.WebRootPath + movie.Poster.Path)) { System.IO.File.Delete(_appEnvironment.WebRootPath + movie.Poster.Path); } movie.Poster = file; } _db.Movies.Update(movie); } else { return(Forbid("Отказано в доступе.")); } } else { _db.Movies.Add(new Movie() { Name = model.Name, Description = model.Description, YearOfIssue = model.YearOfIssue, Director = model.Director, User = user, Poster = file }); } await _db.SaveChangesAsync(); return(RedirectToAction("Index", "Home")); } else { return(View(model)); } }
public async Task <IActionResult> CreateImage(List <IFormFile> filesadd, int width, int height) { if (filesadd == null || filesadd.Count == 0) { return(Ok(new { imgNode = "Không có hình ảnh được chọn", result = false })); } string createFolderDate = DateTime.Now.ToString("yyyy/MM/dd"); string path = _hostingEnvironment.WebRootPath + @"\uploads\" + createFolderDate + ""; CreateFolder(path); if (path == null) { path = "image"; } var filePaths = new List <string>(); string sql = ""; foreach (var formFile in filesadd) { if (FormFileExtensions.IsImage(formFile) && formFile.Length > 0 && formFile.Length <= 4096000) { var filePath = Path.Combine(_hostingEnvironment.WebRootPath, "" + path + ""); filePaths.Add(filePath); var randomname = DateTime.Now.ToFileTime() + Path.GetExtension(formFile.FileName); var fileNameWithPath = string.Concat(filePath, "\\", randomname); using (var stream = new FileStream(fileNameWithPath, FileMode.Create)) { await formFile.CopyToAsync(stream); } Resize(fileNameWithPath, width, height); //FileStream ms; //ms = new FileStream(fileNameWithPath, FileMode.Open); //var auth = new FirebaseAuthProvider(new FirebaseConfig(_firebase.ApiKey)); //var a = await auth.SignInWithEmailAndPasswordAsync(_firebase.AuthEmail, _firebase.AuthPassword); //var cancellation = new CancellationTokenSource(); //var task = new FirebaseStorage( // _firebase.Bucket, // new FirebaseStorageOptions // { // AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken), // ThrowOnCancel = true // }) // .Child($"uploads/" + createFolderDate + "/" + randomname + "") // .PutAsync(ms, cancellation.Token); //task.Progress.ProgressChanged += (s, e) => Console.WriteLine($"Progress: {e.Percentage} %"); // ms.Close(); if (sql.Length > 1) { sql = "" + sql + ",uploads/" + createFolderDate + "/" + randomname + ""; } else { sql = "uploads/" + createFolderDate + "/" + randomname + ""; } } else { return(Ok(new { imgNode = "File được chọn có định dạng không phải là hình ảnh hoặc file được chọn phải có kích thước > 0 và <4M !", result = false })); } } return(Ok(new { imgNode = sql, result = true })); }
public async Task <IActionResult> Snimi(LicniPodaciUrediVM podaci) { try { if (podaci.Lozinka == null || podaci.PotvrdiLozinku == null) { ViewData["error_poruka"] = "Potvrdite izmjene unosom vaše lozinke"; podaci.Slika = Convert.FromBase64String(podaci.StaraSlika); return(View("Uredi", podaci)); } if (podaci.Lozinka != podaci.PotvrdiLozinku) { ViewData["error_poruka"] = "Lozinke se ne podudaraju"; podaci.Slika = Convert.FromBase64String(podaci.StaraSlika); return(View("Uredi", podaci)); } if (!Regex.IsMatch(podaci.KorisnickoIme, @"^[a-z]+$")) { ViewData["error_poruka"] = "Korisničko ime mailm slovima!"; podaci.Slika = Convert.FromBase64String(podaci.StaraSlika); return(View("Uredi", podaci)); } if (await provjeriKorisnickoIme(podaci.KorisnickoIme, podaci.Id.Value)) { ViewData["error_poruka"] = "Ovo korisničko ime nije dozvoljeno"; podaci.Slika = Convert.FromBase64String(podaci.StaraSlika); return(View("Uredi", podaci)); } var update = new PutnikUpsertRequest(); if (podaci.SlikaZaDodat == null) { var data = Convert.FromBase64String(podaci.StaraSlika); update.Slika = data; } else { update.Slika = await FormFileExtensions.GetBytes(podaci.SlikaZaDodat); } update.Ime = podaci.Ime; update.Prezime = podaci.Prezime; update.KorisnickoIme = podaci.KorisnickoIme; update.DatumRegistracije = podaci.DatumRegistracije; update.DatumRodjenja = podaci.DatumRodjenja; update.Lozinka = podaci.Lozinka; update.PotvrdiLozinku = podaci.PotvrdiLozinku; update.Id = podaci.Id.Value; update.Email = podaci.Email; await _putnikService.Update(update.Id, update); return(RedirectToAction("Prikaz")); } catch (Exception ex) { throw new Exception(ex.Message); } }
public async Task <IActionResult> Publish([Bind("Artwork, Document, Tags, ArtworkTag, File, CreativeCommonsId")] ArtworkPublishViewModel viewModel) { // Reinitialisation IQueryable <CreativeCommons> creativeCommons = _context.CreativeCommons; viewModel.CreativeCommons = await creativeCommons.ToListAsync(); if (ModelState.IsValid) { // FILE UPLOAD string uniqueFileName = null; if (viewModel.File != null) { // Verifications content-type, mime-type, scripting etc bool isPicture = FormFileExtensions.IsPicture(viewModel.File, out string errorImage); bool isAudio = FormFileExtensions.IsAudio(viewModel.File, out string errorAudio); bool isPdf = FormFileExtensions.IsPDF(viewModel.File, out string errorPdf); string folder = null; if (isPicture) { folder = "artworks/picture/"; } else if (isAudio) { folder = "artworks/audio/"; } else if (isPdf) { folder = "artworks/pdf/"; } string uploadsFolder = Path.Combine(_hostingEnv.WebRootPath, folder); uniqueFileName = Guid.NewGuid().ToString() + "_" + viewModel.File.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); try { viewModel.File.CopyTo(new FileStream(filePath, FileMode.Create)); } catch (Exception e) { ModelState.AddModelError("error", $"An unexpected error occurred : + {e.Message}"); } // Creating thumbnails for pic if (isPicture) { string uploadsThumbnailAvatarFolder = Path.Combine(_hostingEnv.WebRootPath, "artworks/picture/thumbnails"); string thumbnailFilePath = Path.Combine(uploadsThumbnailAvatarFolder, uniqueFileName); Image image = Image.FromStream(viewModel.File.OpenReadStream(), true, true); double ratio = 200 * 1.0 / image.Width; int newHeight = (int)Math.Floor(image.Height * ratio); var newImage = new Bitmap(200, newHeight); using var thumbnail = Graphics.FromImage(newImage); thumbnail.CompositingQuality = CompositingQuality.HighSpeed; thumbnail.InterpolationMode = InterpolationMode.HighQualityBicubic; thumbnail.CompositingMode = CompositingMode.SourceCopy; thumbnail.DrawImage(image, 0, 0, 200, newHeight); newImage.Save(thumbnailFilePath); } } // SEO-friendly URL SlugHelper helper = new SlugHelper(); string normalizedTitle = helper.GenerateSlug(viewModel.Artwork.Title); Artwork artworkToAdd = new Artwork { Title = viewModel.Artwork.Title, NormalizedTitle = normalizedTitle, Description = viewModel.Artwork.Description, CreationDate = DateTime.Now, ReleaseDate = viewModel.Artwork.ReleaseDate, Privacy = viewModel.Artwork.Privacy, CCLicense = await _context.CreativeCommons.FirstAsync(x => x.CreativeCommonsId == viewModel.CreativeCommonsId), Category = viewModel.Artwork.Category, IsDerivating = viewModel.Artwork.IsDerivating, LinkDerivating = viewModel.Artwork.LinkDerivating, LicenseDerivating = viewModel.Artwork.LicenseDerivating, AuthorDerivating = viewModel.Artwork.AuthorDerivating, Artist = await _userManager.GetUserAsync(User) }; Document documentToAdd = new Document { Media = viewModel.Document.Media, FilePath = uniqueFileName, ContentType = viewModel.File.ContentType.ToLower(), Artwork = artworkToAdd }; _context.Add(artworkToAdd); _context.Add(documentToAdd); // Tag and linking many-to-many char[] delimiterChars = { ',', '.', ';' }; string[] tags = viewModel.Tags.Name.Split(delimiterChars); foreach (string tag in tags) { Tag tagToAdd = new Tag { Name = tag }; ArtworkTag artworkTagToAdd = new ArtworkTag { Artwork = artworkToAdd, Tag = tagToAdd }; _context.Add(tagToAdd); _context.Add(artworkTagToAdd); } await _context.SaveChangesAsync(); // We redirect on the new artwork page then return(RedirectToAction(nameof(Index), new { userName = _userManager.GetUserName(User), title = normalizedTitle })); } return(View(viewModel)); }
public async Task <IActionResult> ModificarAnime(int id, [FromBody] AnimeEditarViewModel anime) { if (id != anime.AnimeId) { return(BadRequest(new ApiResponseFormat() { Estado = StatusCodes.Status400BadRequest, Mensaje = $"Los Ids no coinciden {id} y {anime.AnimeId}" })); } Anime modificado = await _context.Animes.Include(a => a.Generos).ThenInclude(g => g.Genero).Include(a => a.Episodios).FirstOrDefaultAsync(a => a.AnimeId == anime.AnimeId); modificado.Nombre = anime.Nombre; modificado.Numero_episodios = anime.Numero_episodios; modificado.Descripcion = anime.Descripcion; modificado.Fecha_publicacion = anime.Fecha_publicacion; string mensajePortadaInvalida = "."; if (anime.Portada != null) { if (FormFileExtensions.IsImage(anime.Portada)) { MemoryStream ms = new MemoryStream(); anime.Portada.CopyTo(ms); modificado.Portada = ms.ToArray(); } else { mensajePortadaInvalida = " pero el formato de imagen invalido, se pondra la imagen de portada default."; } } await AniadirGeneros(modificado, anime.GenerosActivos.Where(ga => ga.Activo).Select(ga => ga.Genero).ToList()); _context.Entry(modificado).State = EntityState.Modified; try { await _context.SaveChangesAsync(); return(Ok(new ApiResponseFormat() { Estado = StatusCodes.Status200OK, Mensaje = $"Anime {modificado.Nombre} modificado exitosamente{mensajePortadaInvalida}", Dato = anime })); } catch (DbUpdateConcurrencyException ex) { if (!AnimeExists(id)) { return(NotFound(new ApiResponseFormat() { Estado = StatusCodes.Status404NotFound, Mensaje = $"No se encontro ningun anime con el Id {id}" })); } else { return(StatusCode(StatusCodes.Status304NotModified, new ApiResponseFormat() { Estado = StatusCodes.Status304NotModified, Mensaje = ex.Message })); } } }
public async Task <IActionResult> Registracija(RegistracijaVM podaci) { if (!ModelState.IsValid) { return(View("RegistrujSe", podaci)); } if (podaci.Slika != null) { ViewData["error_poruka"] = "Molimo da unesete i sliku!"; return(View("RegistrujSe", podaci)); } if (podaci.Slika != null && podaci.Slika.Length == 0) { ViewData["error_poruka"] = "Molimo da unesete i sliku!"; return(View("RegistrujSe", podaci)); } if (podaci.Lozinka != podaci.PotvrdiLozinku) { ViewData["error_poruka"] = "Lozinke se ne podudaraju"; return(View("RegistrujSe", podaci)); } try { var niz = await FormFileExtensions.GetBytes(podaci.Slika); //DODATI I KORISNICKO IME NA FORMU var newPuntik = new PutnikUpsertRequest() { KorisnickoIme = podaci.KorisnickoIme, Ime = podaci.Ime, Prezime = podaci.Prezime, DatumRegistracije = DateTime.Now, DatumRodjenja = podaci.DatumRodjenja, Email = podaci.Email, Lozinka = podaci.Lozinka, PotvrdiLozinku = podaci.PotvrdiLozinku, Slika = niz }; await _putnikService.Insert(newPuntik); APIService.Username = newPuntik.KorisnickoIme; APIService.Password = newPuntik.Lozinka; return(RedirectToAction("PrikaziNotifikacije", "Notifikacije")); } catch (Exception e) { throw new Exception(e.Message); } }
public async Task <IActionResult> OnPostAsync() { var user = await this.userManager.GetUserAsync(this.User); if (user == null) { return(this.NotFound($"{UnableToLoadUser} '{this.userManager.GetUserId(this.User)}'.")); } if (!this.ModelState.IsValid) { await this.LoadAsync(user); return(this.Page()); } var phoneNumber = await this.userManager.GetPhoneNumberAsync(user); if (this.Input.PhoneNumber != phoneNumber) { var setPhoneResult = await this.userManager.SetPhoneNumberAsync(user, this.Input.PhoneNumber); if (!setPhoneResult.Succeeded) { this.StatusMessage = PhoneError; return(this.RedirectToPage()); } } var firstName = user.FirstName; var lastName = user.LastName; var education = user.Education; var companyName = user.CompanyName; var interests = user.Interest; var contacts = user.Contact; var websiteUrl = user.WebsiteUrl; var githubUrl = user.GithubUrl; var facebookUrl = user.FacebookUrl; var instagramUrl = user.InstagramUrl; if (this.Input.FirstName != firstName) { user.FirstName = this.Input.FirstName; } if (this.Input.LastName != lastName) { user.LastName = this.Input.LastName; } if (this.Input.Education != education) { user.Education = this.Input.Education; } if (this.Input.ComponyName != companyName) { user.CompanyName = this.Input.ComponyName; } if (this.Input.Interest != interests) { user.Interest = this.Input.Interest; } if (this.Input.Contact != contacts) { user.Contact = this.Input.Contact; } if (this.Input.WebsiteUrl != websiteUrl) { user.WebsiteUrl = this.Input.WebsiteUrl; } if (this.Input.GithubUrl != githubUrl) { user.GithubUrl = this.Input.GithubUrl; } if (this.Input.FacebookUrl != facebookUrl) { user.FacebookUrl = this.Input.FacebookUrl; } if (this.Input.InstagramUrl != instagramUrl) { user.InstagramUrl = this.Input.InstagramUrl; } if (this.Input.UploadPicture != null) { string picturePath = $"{this.environment.WebRootPath}{ProfilePicturePath}"; await this.profileServices.SetProfilePictureAsync( user.Id, await FormFileExtensions.GetBytesAsync(this.Input.UploadPicture), Path.GetExtension(this.Input.UploadPicture.FileName), picturePath); } await this.userManager.UpdateAsync(user); await this.signInManager.RefreshSignInAsync(user); this.StatusMessage = UpdatedSuccessfully; return(this.RedirectToPage()); }