【问题标题】:How to convert IFormFile to byte[] in a C#?如何在 C# 中将 IFormFile 转换为 byte[]?
【发布时间】:2019-11-15 14:59:49
【问题描述】:

我收到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 [] 
    };
}

我已经尝试了一些方法,但我什至不确定我是否可以按照我尝试的方式将 IFormFile 转换为 byte[],不确定这是否是正确的方法。

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

【问题讨论】:

标签: c# .net-core multipartform-data iformfile


【解决方案1】:

我有一个扩展:

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

【讨论】:

  • 为什么不改用input.CopyTo(ms);,或者如果你真的想强制使用16k缓冲区,那么input.CopyTo(ms, 16 * 1024);
  • 有道理,但结果是一样的
  • 感谢您之前与类似讨论相关的评论。 .CopyTo 在 4.0 之前的 .NET 中不可用,因此如果您需要在此之前支持 .NET,则必须改为执行上述操作。
猜你喜欢
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多