首页 > 解决方案 > 如何将文件图像转换为字节 [] ReactJS?

问题描述

我想将图像发送到 api 端点和端点接受字节 [] 我该如何处理。我的代码是:点击上传按钮时的 ReactJS 函数:

    let onClickHandler = () => {
        let data = new FormData()
        data.append('file', image);

        axios.post("/Contact/ContactForm/",  {
            
            AttachedImage: data

        }, {
            
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'X-Requested-With': 'XMLHttpRequest',
                }
            // receive two parameter endpoint url ,form data
        })
            .then(res => { // then print response status
                console.log('binary Response......',res.statusText)
            });
}

和我的端点控制器方法:

[HttpPost]
        public async Task<IActionResult> ContactForm([FromBody] Contact model)
        {
            try
            {
                model.CreationDate = DateTime.Now;
                await _contact.ContactForm(model);
                return Ok("Submitted Successfully");
            }
            catch (Exception ex) { return this.BadRequest("Not Submitted Successfully" + ex.ToString()); }
        }

最后是 Model.cs 类

public byte[] AttachedImage { set; get; }

标签: javascriptreactjsaxiosasp.net-core-webapibinaryfiles

解决方案


想将图像发送到 api 端点和端点接受字节 [] 我该如何处理。

请注意,默认模型绑定器无法处理将设置为的字节数组null

要上传图像文件并将数据绑定到模型类的字节数组属性,您可以尝试以下解决方案:

解决方案1 ​​- 将所选图像文件转换为base64编码字符串,并使用aByteArrayModelBinder将其转换为字节数组。

public class Contact
{
    [ModelBinder(BinderType = typeof(ByteArrayModelBinder))]
    public byte[] AttachedImage { set; get; }
    public DateTime CreationDate { set; get; }

    //...
    //other properties
    //...
 }

测试数据

{
    "attachedImage": "iVBORw0KGgoAAAANSUhEUgAAAMsAAA.....",
    "creationDate": "2021-08-21T15:12:05"
}

测试结果

在此处输入图像描述

解决方案 2 - 实现并使用如下所示的自定义模型绑定器将选定的图像文件绑定到字节数组。

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["AttachedImage"]?.Length > 0)
        {
            var fileBytes = new byte[bindingContext.ActionContext.HttpContext.Request.Form.Files["AttachedImage"].Length];

            using (var ms = new MemoryStream())
            {
                bindingContext.ActionContext.HttpContext.Request.Form.Files["AttachedImage"].CopyTo(ms);
                fileBytes = ms.ToArray();
            }

            bindingContext.Result = ModelBindingResult.Success(fileBytes);
        }



        return Task.CompletedTask;
    }
}

测试结果

在此处输入图像描述


推荐阅读