使用JSON asp.net核心api上传多部分/表单数据图像 [英] Multipart/form-data images upload with JSON asp.net core api

查看:114
本文介绍了使用JSON asp.net核心api上传多部分/表单数据图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单个POST中同时发布图像和JSON的最佳方法是什么? (使用多部分) 我有一个表单,其中包含一些放入JSON的数据,用户可以添加0到6张照片并将其提交给API.

What's the best way to POST both images and JSON at the same time in a single POST ? (using multipart) I have a form with some data that i put into JSON and the users can add 0 to 6 photos and submit it to the API.

有人可以解释我该怎么做吗?

Can someone explain me how to do it ?

这是我的代码,感谢您的帮助:

Edit : Here is my code thanks to your help :

    // POST api/<controller>
    [HttpPost, Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public IActionResult Post(ViewModel vm)
    {
        IActionResult response = Unauthorized();

        var data = vm.FamilleProduit;
        var reforigine = vm.RefOrigine;

        if (vm.Images != null)
        {
            foreach (var image in vm.Images)
            {
                byte[] fileData = null;

                // read file to byte array
                using (var binaryReader = new BinaryReader(image.OpenReadStream()))
                {
                    fileData = binaryReader.ReadBytes((int)image.Length);
                }
            }
        }
        return response;
    }

    public class ViewModel
    {
        public string FamilleProduit { get; set; }
        public string RefOrigine { get; set; }
        public List<IFormFile> Images { get; set; }
    }

我正在用Postman和i POST测试2个文本(FamilleProduit和RefOrigine)和2个带有"multipart/form-data"的文件(2个图像). 我完美地得到了2个文本,但是图像"字段每次都为空.

I'm testing with Postman and i POST 2 text (FamilleProduit & RefOrigine) and 2 files (2 images) with "multipart/form-data". I get the 2 texts perfectly but Images field is null everytime.

谢谢, 特里斯坦.

推荐答案

您可以使用内置类IFormFile轻松处理文件上传.要将其与JSON一起使用,您可以创建自定义模型联编程序,并将其结合到DTO对象中:

You can use built-in class IFormFile to easily work with file upload. To use it together with JSON you may create custom model binder and combine it together in DTO object:

public class ViewModel
{
    [ModelBinder(BinderType = typeof(FormDataJsonBinder))]
    public DataModel Data { get;set; }

    public List<IFormFile> Images { get; set; }
}

public class FormDataJsonBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if(bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }    

        string fieldName = bindingContext.FieldName;
        var valueProviderResult = bindingContext.ValueProvider.GetValue(fieldName);

        if(valueProviderResult == ValueProviderResult.None)
        {
            return Task.CompletedTask;
        }
        else
        {
            bindingContext.ModelState.SetModelValue(fieldName, valueProviderResult);
        }    

        string value = valueProviderResult.FirstValue;
        if(string.IsNullOrEmpty(value))
        {
            return Task.CompletedTask;
        }

        try
        {                
            object result = JsonConvert.DeserializeObject(value, bindingContext.ModelType);
            bindingContext.Result = ModelBindingResult.Success(result);
        }
        catch(JsonException)
        {
            bindingContext.Result = ModelBindingResult.Failed();
        }

        return Task.CompletedTask;
    }
}

然后您可以在控制器中使用它:

Then you can work with it in your controller:

[HttpPost]
public IActionResult Create(ViewModel vm)
{
    var data = vm.Data;

    if (vm.Images != null)
    {
        foreach(var image in vm.Images)
        {
            byte[] fileData = null;

            // read file to byte array
            using (var binaryReader = new BinaryReader(image.OpenReadStream()))
            {
                fileData = binaryReader.ReadBytes((int)image.Length);
            }
        }
    }
}

这篇关于使用JSON asp.net核心api上传多部分/表单数据图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆