簡體   English   中英

如何將 IFormFile 轉換為 C# 中的 byte[]?

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

我收到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[] ,不確定它是否是正確的方法。

無論如何,感謝您的幫助。

我有一個擴展:

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()
            };
        }
    }
  1. 您似乎正在發回內存流而不是字節數組。
  2. stream.ToArray() 返回一個字節數組,您可以使用

所以,你的代碼應該是

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