【问题标题】:How to Convert File Image to Byte[] ReactJS?如何将文件图像转换为字节 [] ReactJS?
【发布时间】:2021-10-19 01:48:01
【问题描述】:

我想将图像发送到 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; }

【问题讨论】:

标签: javascript reactjs axios asp.net-core-webapi binaryfiles


【解决方案1】:

很难知道 API 是否会接受它,但您可以将文件转换为 Uint8Array,它是一个数组,文件的所有字节都表示为整数。

let file: File = ...
let uint8 = new Uint8Array(await file.arrayBuffer())

【讨论】:

  • 嗨,它不工作。在我的接收端,“byte[] AttachedImage”用于存储图像。我需要以 byte[] AttachedImage 接受的方式转换图像。
【解决方案2】:

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

请注意the default model binder 无法处理将设置为null 的字节数组。

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

方案一 - 将选中的图片文件转换为base64编码的字符串,并使用ByteArrayModelBinder将其转换为字节数组。

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;
    }
}

测试结果

【讨论】:

  • 感谢您的解决方案。解决方案 1 对我有用。顺便说一句,在客户端,我们可以通过以下方式将图像转换为字节: const img = btoa(image);
猜你喜欢
  • 2011-03-07
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
  • 2014-01-13
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
相关资源
最近更新 更多