简体   繁体   English

如何将 IFormFile 转换为 C# 中的 byte[]?

[英]How to convert IFormFile to byte[] in a C#?

I receive IFormFile and I would like to convert it to byte[] , my code looks like this:我收到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 [] 
    };
}

I've tried something but I'm not even sure if I can convert IFormFile to byte[] on way I tried, not sure if it's right approach.我已经尝试过一些东西,但我什至不确定我是否可以按照我尝试的方式将IFormFile转换为byte[] ,不确定它是否是正确的方法。

Anyway, thanks for any help.无论如何,感谢您的帮助。

I have an extension for it:我有一个扩展:

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

then然后

  if (file != null)
  { 
        using (var stream = file.OpenReadStream())
        {
            return new ProductDto
            {
                product_resp = JsonConvert.SerializeObject(product).ToString(),
                file_data = stream.ToByteArray()
            };
        }
    }
  1. You seem to be sending back the memorystream instead of a byte array.您似乎正在发回内存流而不是字节数组。
  2. stream.ToArray() returns a byte array you can use stream.ToArray() 返回一个字节数组,您可以使用

So, your code should be所以,你的代码应该是

private ProductDto GenerateData(Request product, IFormFile file)
{
    byte[] fileByteArray;    //1st change here
    if (file != null)
    { 
        using (var item = new MemoryStream())
        {
            file.CopyTo(item);
            fileByteArray = item.ToArray(); //2nd change here
        }
    }

    return new ProductDto
    {
        product_resp = JsonConvert.SerializeObject(product).ToString(),
        file_data = fileByteArray; // 3rd change here
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM