0

enter image description here

enter image description here

enter image description here

enter image description here

As you can see I want to add directly image file to the sql server by getting id, carId, uploadDate as Json and imagePath as file byte array. How can I do that what should I change ?

1
  • 3
    declare ImagePath as IFormFile Commented Feb 27, 2021 at 16:38

1 Answer 1

1

The default model binder can not handle byte arrays that would be set to null.

As @viveknuna mentioned, if possible, you can try to use IFormFile to process or save the uploaded file.

Besides, if you really want to bind selected file to byte arrays, you can try to implement and use a custom model binder, like below.

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["ImagePath"]?.Length > 0)
        {
            var fileBytes = new byte[bindingContext.ActionContext.HttpContext.Request.Form.Files["ImagePath"].Length];

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

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


            
        return Task.CompletedTask;
    }
}

Apply the ModelBinder attribute to model property

[ModelBinder(BinderType = typeof(ImageToByteArrayModelBinder))]
public byte[] ImagePath { get; set; }

Test Result

enter image description here

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

1 Comment

I changed my controller a bit [HttpPost("add")] public async Task<IActionResult> Add([FromForm] CarImage carImage, IFormFile imageFile) so I get FormFile then I convert it to byte array It works fine now thank you public static async Task<byte[]> ConvertFormFileToByteArray(IFormFile formFile) { using (var memoryStream = new MemoryStream()) { await formFile.CopyToAsync(memoryStream); byte[] imageBytes = memoryStream.ToArray(); return imageBytes; } }

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.