gpt4 book ai didi

c# - 无法将 HttpPostedFileBase 对象转换为字节数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:13:49 25 4
gpt4 key购买 nike

我正在尝试创建一种方法,我可以在其中传递图像文件并检索该图像文件的字节,以便稍后我可以将字节存储在数据库中。这是我的方法代码。

private byte[] GetImageBytes(HttpPostedFileBase ProfilePhoto)
{
if (ProfilePhoto != null)
{
using (MemoryStream ms = new MemoryStream())
{
ProfilePhoto.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
return array;
}
}
else
{
return null;
}
}

问题是我得到了一个字节数组array[0],所以没有任何东西被转换成字节。在 Debug模式下,我可以看到 ProfilePhoto 不为 null 并且它具有 Length 属性等...我尝试了另一种方法,将方法中的代码替换为以下代码:

byte[] image = new byte[ProfilePhoto.ContentLength];
ProfilePhoto.InputStream
.Read(image, 0, Convert.ToInt32(ProfilePhoto.ContentLength));
return image;

但还是没有成功。它返回一个数组 0x0000... 这是默认值。知道如何解决这个问题吗?可能很简单,但我不知道如何在 MVC 中上传文件


.我试图找到其他方法来做到这一点,但没有一个奏效。

最佳答案

在复制之前,您需要先查找到流的开头:

ProfilePhoto.InputStream.Seek(0, SeekOrigin.Begin);
ProfilePhoto.InputStream.CopyTo(ms);

关于c# - 无法将 HttpPostedFileBase 对象转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37975559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com