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 Answer
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
1 Comment
ZootHii
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; } }





ImagePathasIFormFile