c# - 如何在 C# 中将 IFormFile 转换为 byte[]?
问题描述
我收到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()
};
}
}
推荐阅读
- javascript - 有没有办法降低我必须请求大量 ID 的 HTTPS 请求
- azure-active-directory - 通过 API MS 图访问 onenote
- ios - Tableview 中的 CollectionView 为重用的单元格加载不正确的数据
- flutter - 如何在 Flutter 中填充 IconButton 的颜色
- reactjs - 覆盖材质 UI 道具类型
- java - 我需要将主类中的变量用于我创建的另一个类
- javascript - 推送后元素未显示在数组中
- karma-runner - 找不到插件“karma-webpack”
- r - Tidymodels:使用 R 中的函数 collect_predictions() 和 ggplot() 绘制预测值与真实值
- git - 设置 git 全局添加某些类型的文件