无法将上传的图像转换为字节数组

unable to convert uploaded image to byte array

我正在尝试将上传的图像转换为字节数组,以便将其存储在数据库中 table。

下面的代码用于执行从图像到字节数组的转换:

public byte[] ConvertToBytes(HttpPostedFileBase image)
{
     BinaryReader reader = new BinaryReader(image.InputStream);
     var imageBytes = reader.ReadBytes((int)image.ContentLength);
     return imageBytes;
}

当我在此代码上放置断点以查看返回的内容时,imageBytes 变量显示 {byte[0]}。

下面显示的代码是我用来上传此图片的视图的控制器中的接收 ActionResult(目前我正在使用文件输入 select 并上传图片):

[HttpPost]
public ActionResult NewsManager(NewsManagerViewModel model)
{
    var newsManagerRepository = new NewsManagerRepository();
    var currentUser = User.Identity.Name;

    if (ModelState.IsValid)
    {
        HttpPostedFileBase file = Request.Files["ImageData"];

        var fileIsImage = file.IsImage();

        if (fileIsImage)
        {
            model.Author = currentUser;

            var newsUploaded = newsManagerRepository.UploadNews(file, model);

            if (newsUploaded == 1)
            {
                return View();
                }

                ModelState.AddModelError("uploadFailed", "News item was not uploaded");

                return View(model);
                }
                ModelState.AddModelError("fileNotImage", "the file you have uploaded is not an image");

                return View(model);
            }

            return View(model);
        }

有人知道为什么我正在转换的图像没有成功转换为字节数组吗?

任何建议将不胜感激,该应用程序目前是 MVC 5 和 .net 4.5 版。


调用方法代码如下:

public int UploadNews(HttpPostedFileBase file, NewsManagerViewModel model)
{
    model.BannerImage = ConvertToBytes(file);
    var ndtms2Utils = new NDTMS2UtilsEntities();

    var news = new News
    {
        Title = model.Title,
        Author = model.Author,
        BannerImage = model.BannerImage,
        DateCreated = DateTime.Now,
        NewsContent = model.NewsContent
    };

    ndtms2Utils.News.Add(news);
    int i = ndtms2Utils.SaveChanges();
    if (i == 1)
    {
        return 1;
    }
    return 0;
}

使用下面提到的转换方法:

public byte[] ConvertToBytes(HttpPostedFileBase image)
{
   return image.InputStream.StreamToByteArray();
}

public static byte[] StreamToByteArray(this Stream input)
{
    input.Position = 0;
    using (var ms = new MemoryStream())
    {
        int length = System.Convert.ToInt32(input.Length);
        input.CopyTo(ms, length);
        return ms.ToArray();
    }
}