首页 > 解决方案 > 如何在邮递员 webAPI 中添加带有图像字节数组的 Json 文件

问题描述

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

如您所见,我想通过将 id、carId、uploadDate 作为 Json 并将 imagePath 作为文件字节数组来直接将图像文件添加到 sql 服务器。我该怎么做我应该改变什么?

标签: c#jsonimageasp.net-corepostman

解决方案


默认模型绑定器无法处理将设置为的字节数组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; }

测试结果

在此处输入图像描述


推荐阅读