MVC:图像显示为字节数组的错误

时间:2018-04-19 02:01:29

标签: c# sql asp.net asp.net-mvc razor

出现问题,我的图片显示为错误。尝试了将字节数组转换为图像的两种方法。任何帮助表示赞赏。

查看:

        if (product.ImageUploadBytes != null)
        {
            var base64 = Convert.ToBase64String(product.ImageUploadBytes);
            var imgSrc = String.Format("data:image/gif;base64,{0}", base64);

            <div class="panel-body"><img src=@imgSrc /></div>
            <img src="@Url.Action("GetImage", "Products", new { id = product.ID })" />
        }

控制器:

    public ActionResult GetImage(int imageID)
    {
        Product p = new Product();
        p = _context.Products.FirstOrDefault(x => x.ID == imageID);

        if (p.ImageUploadBytes != null)
        {
            return File(p.ImageUploadBytes, "image/png");
        }
        else
        {
            return null;
        }
    }

数据库中的字节数组:Image

图像上传到DB:

    [HttpPost]
    public ActionResult AddImage(Product model, HttpPostedFileBase image)
    {
        if (image != null)
        {
            model.ImageUploadBytes = new byte[image.ContentLength];
            image.InputStream.Read(model.ImageUploadBytes, 0, image.ContentLength);
        }
        _context.Products.Add(model);
        _context.SaveChanges();


        return View(model);
    }

0 个答案:

没有答案