Search code examples
c#asp.net-mvcasp.net-coremodel-view-controllerhttppostedfilebase

como puedo usalor HttpPostedFileBase en asp.net core?


HttpPostedFileBase

I want to solve this problem to store the image to the database. I still don't run the project, if I have errors or an easier way to do it

 public IActionResult Create(Productos prod [Bind("codigoFoto"] Productos productos, HttpPostedFileBase FotoProducto) 
        {
            //Console.WriteLine(JObject.FromObject(prod));
            using (var _context = new ApplicationDbContext())
            {
                var Categoria = _context.Categorias.Where(i => i.IsActive && i.Id == prod.Categoria.Id).FirstOrDefault(); 
                if (prod != null)
                {
                    if (FotoProducto != null && FotoProducto.ContentLength > 0)
                    {
                        byte[] imageData = null;

                        using (var binaryReader = new BinaryReader(FotoProducto.InputStream))
                        {
                            imageData = binaryReader.ReadBytes(FotoProducto.ContentLength);
                        }
                        //setear la imagen a la entidad que se creara
                        productos.Foto = imageData;
                    }

Solution

  • Thank you very much this served me

    Create(Productos prod [Bind("codigoFoto"] Productos productos, IFormFile FotoProducto)
    

    but I also had to make a change to this code

    using (var binaryReader = new BinaryReader(FotoProducto.InputStream))
    
    var filePath = Path.GetTempFileName();
                        var file = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    
                        file = Path.Combine(file, FotoProducto.FileName);
    
    
                        using (var stream = new FileStream(file, FileMode.Create))