簡體   English   中英

如何在 postman webAPI 中添加帶有圖像字節數組的 Json 文件

[英]How to add Json file with image byte array in postman webAPI

在此處輸入圖像描述

在此處輸入圖像描述

在此處輸入圖像描述

在此處輸入圖像描述

如您所見,我想通過獲取 id、carId、uploadDate 作為 Json 和 imagePath 作為文件字節數組,直接將圖像文件添加到 sql 服務器。 我該怎么做我應該改變什么?

默認的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM