Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

379
Vistas
How to Convert File Image to Byte[] ReactJS?

I want to send image to api end point and end point accept byte[] how can i handle this. My code is: ReactJS function on upload button click:

    let onClickHandler = () => {
        let data = new FormData()
        data.append('file', image);

        axios.post("/Contact/ContactForm/",  {
            
            AttachedImage: data

        }, {
            
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'X-Requested-With': 'XMLHttpRequest',
                }
            // receive two parameter endpoint url ,form data
        })
            .then(res => { // then print response status
                console.log('binary Response......',res.statusText)
            });
}

and my endpoint controller method:

[HttpPost]
        public async Task<IActionResult> ContactForm([FromBody] Contact model)
        {
            try
            {
                model.CreationDate = DateTime.Now;
                await _contact.ContactForm(model);
                return Ok("Submitted Successfully");
            }
            catch (Exception ex) { return this.BadRequest("Not Submitted Successfully" + ex.ToString()); }
        }

and finally Model.cs Class

public byte[] AttachedImage { set; get; }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

want to send image to api end point and end point accept byte[] how can i handle this.

Please note that the default model binder can not handle byte array that would be set to null.

To upload image file and bind the data to a byte array property of your model class, you can try following solutions:

Solution 1 - convert the selected image file to base64 encoded string, and use a ByteArrayModelBinder to convert it into a byte array.

public class Contact
{
    [ModelBinder(BinderType = typeof(ByteArrayModelBinder))]
    public byte[] AttachedImage { set; get; }
    public DateTime CreationDate { set; get; }

    //...
    //other properties
    //...
 }

Testing Data

{
    "attachedImage": "iVBORw0KGgoAAAANSUhEUgAAAMsAAA.....",
    "creationDate": "2021-08-21T15:12:05"
}

Testing Result

enter image description here

Solution 2 - implement and use a custom model binder like below to bind selected image file to byte array.

public class ImageToByteArrayModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        // ...
        // implement it based on your actual requirement
        // code logic here
        // ...



        if (bindingContext.ActionContext.HttpContext.Request.Form.Files["AttachedImage"]?.Length > 0)
        {
            var fileBytes = new byte[bindingContext.ActionContext.HttpContext.Request.Form.Files["AttachedImage"].Length];

            using (var ms = new MemoryStream())
            {
                bindingContext.ActionContext.HttpContext.Request.Form.Files["AttachedImage"].CopyTo(ms);
                fileBytes = ms.ToArray();
            }

            bindingContext.Result = ModelBindingResult.Success(fileBytes);
        }



        return Task.CompletedTask;
    }
}

Testing Result

enter image description here

about 4 years ago · Juan Pablo Isaza Denunciar

0

It's hard to know if the API will accept it, but you can convert the file to a Uint8Array which is an array with all bytes of the file represented as Integers.

let file: File = ...
let uint8 = new Uint8Array(await file.arrayBuffer())
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda