【问题标题】:Can not convert HttpPostedFileBase object into byte array无法将 HttpPostedFileBase 对象转换为字节数组
【发布时间】:2016-10-24 20:09:19
【问题描述】:

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

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;
    }
}

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

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

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


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

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 image-uploading


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,解决了我的问题。等效地,我以第二种方式发现了问题。我必须做ProfilePhoto.InputStream.Position = 0; 然后一切正常:) 干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2018-02-14
    • 2016-10-31
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    相关资源
    最近更新 更多