2

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks For your Solution. Solution 1 is working for me. By the way, in client-side, we can convert image to byte by: const img = btoa(image);
1

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())

1 Comment

hi, it is not working. On my receiving end "byte[] AttachedImage" is used to store the image. I need to convert the image in a way that is byte[] AttachedImage accepted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.