问题
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;
}
}
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;
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.
回答1:
You need to seek to the start of the stream first, before copying it:
ProfilePhoto.InputStream.Seek(0, SeekOrigin.Begin);
ProfilePhoto.InputStream.CopyTo(ms);
来源:https://stackoverflow.com/questions/37975559/can-not-convert-httppostedfilebase-object-into-byte-array