c# - 如何在邮递员 webAPI 中添加带有图像字节数组的 Json 文件
解决方案
默认模型绑定器无法处理将设置为的字节数组null
。
正如@viveknuna 提到的,如果可能的话,您可以尝试使用IFormFile
来处理或保存上传的文件。
此外,如果您真的想将选定的文件绑定到字节数组,您可以尝试实现和使用自定义模型绑定器,如下所示。
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 属性应用于模型属性
[ModelBinder(BinderType = typeof(ImageToByteArrayModelBinder))]
public byte[] ImagePath { get; set; }
测试结果
推荐阅读
- c++ - 如何在创建/销毁之前/之后检查 cudastream 的状态?
- python - 在 Windows 上使用 / 作为路径,并让 stdlib 函数也使用它(glob、os.path 等)
- hybris - 辅助服务模块未在 Spartacus B2B 中与 SAP Commerce cloud 2005/2011 (Hybris) 一起运行
- javascript - 在 Typescript 中为现有类型扩展并添加新属性
- sql-server - VBA Excel - SQL“执行”方法触发查询超时过期
- c# - Sqlite 批量插入新事务
- php - Json 用特殊字符编码
- ffmpeg - 使用特定的叠加起始位置从左到右移动叠加
- php - 返回 eloquent 模型关系时获取空值
- typescript - 打字稿,无法读取存储在 sessionStorage 中的数组