2

I receive IFormFile and I would like to convert it to byte[], my code looks like this:

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.

Anyway, thanks for any help.

demo
  • 6,038
  • 19
  • 75
  • 149
Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102
  • 1
    Does this answer your question? [How to convert a file into byte array in memory?](https://stackoverflow.com/questions/36432028/how-to-convert-a-file-into-byte-array-in-memory) – demo Nov 15 '19 at 15:02
  • Hi @Roxy'Pro Did you solve the problem or not? – Robert N. Dean Nov 20 '19 at 19:11

2 Answers2

2

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()
            };
        }
    }
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • 1
    Why not use `input.CopyTo(ms);` instead, or if you really want to enforce a 16k buffer, then `input.CopyTo(ms, 16 * 1024);`? – Robert McKee Nov 15 '19 at 15:10
  • make sense, but result will be the same – Roman Marusyk Nov 15 '19 at 15:15
  • 1
    Thanks for your previous comment which linked to similar discussion. `.CopyTo` wasn't available in .NET before 4.0, so if you need to support .NET prior to that you had to do the above instead. – Robert McKee Nov 15 '19 at 15:16
0
  1. You seem to be sending back the memorystream instead of a byte array.
  2. stream.ToArray() returns a byte array you can use

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
    };
}
Ash
  • 5,786
  • 5
  • 22
  • 42