[英]How to add Json file with image byte array in postman webAPI
默認的 model binder無法處理將設置為null
。
正如@viveknuna 提到的,如果可能,您可以嘗試使用IFormFile
來處理或保存上傳的文件。
此外,如果您真的想將選定的文件綁定到字節 arrays,您可以嘗試實現並使用自定義 model binder ,如下所示。
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;
}
}
將 ModelBinder 屬性應用於 model 屬性
[ModelBinder(BinderType = typeof(ImageToByteArrayModelBinder))]
public byte[] ImagePath { get; set; }
測試結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.