[英]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()
};
}
}
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.