无法将HttpPostedFileBase对象转换为字节数组 [英] Can not convert HttpPostedFileBase object into byte array
问题描述
我正在尝试创建一种方法,在该方法中我可以传递图像文件并检索该图像文件的字节,因此以后可以将字节存储在数据库中.这是我的方法代码.
I am trying to create a method where I can pass an image file and retrieve bytes of that image file, so later I can store the bytes in database. Here is my code for the method.
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],所以没有任何东西转换成字节.在调试模式下,我可以看到ProfilePhoto不为null,并且具有Length属性等.我尝试了另一种方法,将方法内部的代码替换为以下代码:
The problem is that I get an array of bytes array[0], so there is nothing converted into bytes. In debug mode I can see that the ProfilePhoto is not null and it has Length property etc... I tried another way by replacing the code inside the method with the code below:
byte[] image = new byte[ProfilePhoto.ContentLength];
ProfilePhoto.InputStream
.Read(image, 0, Convert.ToInt32(ProfilePhoto.ContentLength));
return image;
但同样没有成功.它返回一个数组0x0000 ...,这是默认值. 知道如何解决这个问题吗?可能很简单,但我不了解如何在MVC中上传文件
but again no success. It returns an array 0x0000... which is the default value. Any idea how to solve this problem ? Probably it is very simple but I do not have knowledge on how to upload files in MVC
.我试图找到其他方法来做到这一点,但没有一个起作用.
. I tried to find other ways to do that but none of them worked.
推荐答案
复制之前,您需要先搜索流的开头:
You need to seek to the start of the stream first, before copying it:
ProfilePhoto.InputStream.Seek(0, SeekOrigin.Begin);
ProfilePhoto.InputStream.CopyTo(ms);
这篇关于无法将HttpPostedFileBase对象转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!