Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
        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
                }));
            }
        }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
        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));
        }
Exemplo n.º 5
0
        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);
        }
Exemplo n.º 6
0
        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
            }));
        }
Exemplo n.º 7
0
        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
                    }));
                }
            }
        }