Search code examples
javascriptreactjsaxiosasp.net-core-webapibinaryfiles

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; }

Solution

  • 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