Can not convert HttpPostedFileBase object into byte array

让人想犯罪 __ 提交于 2019-12-24 06:05:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!