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

时间:2015-06-04 09:55:17

标签: c# bytearray binaryreader httppostedfilebase

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

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

Run Custom Tool

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

下面显示的代码是控制器中接收的ActionResult,用于上传此图像的视图(目前我正在使用文件输入来选择和上传图像):

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

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

非常感谢任何建议,该应用程序目前是MVC 5和.net 4.5版。

调用方法代码如下:

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

1 个答案:

答案 0 :(得分:1)

使用如下所述的convert方法:

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