首页 > 解决方案 > 如何在 C# 中将 IFormFile 转换为 byte[]?

问题描述

我收到IFormFile并想将其转换为byte[],我的代码如下所示:

private ProductDto GenerateData(Request product, IFormFile file)
{
    if (file != null)
    { 
        using (var item = new MemoryStream())
        {
            file.CopyTo(item);
            item.ToArray();
        }
    }

    return new ProductDto
    {
        product_resp = JsonConvert.SerializeObject(product).ToString(),
        file_data = item; // I need here byte [] 
    };
}

我尝试了一些东西,但我什至不确定我是否可以转换IFormFilebyte[]我尝试过的方式,不确定这是否是正确的方法。

无论如何,感谢您的帮助。

标签: c#.net-coremultipartform-dataiformfile

解决方案


我有一个扩展:

public static byte[] ToByteArray(this Stream input)
{
        byte[] buffer = new byte[16 * 1024];
        using (var ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
}

然后

  if (file != null)
  { 
        using (var stream = file.OpenReadStream())
        {
            return new ProductDto
            {
                product_resp = JsonConvert.SerializeObject(product).ToString(),
                file_data = stream.ToByteArray()
            };
        }
    }

推荐阅读