C# 如何在MVC中从数据库检索图像?

C# 如何在MVC中从数据库检索图像?,c#,asp.net-mvc,varbinary,C#,Asp.net Mvc,Varbinary,我一直在开发一个系统,允许我们的用户将图像上传到数据库中。将图像上传到数据库似乎工作正常,但我似乎无法将图像取回并显示在我的视图中。我没有收到任何错误消息,图像根本不显示。这是到目前为止我的代码 控制器/创建方法 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(UserAccount userAccount, HttpPostedFileBase upload) {

我一直在开发一个系统,允许我们的用户将图像上传到数据库中。将图像上传到数据库似乎工作正常,但我似乎无法将图像取回并显示在我的视图中。我没有收到任何错误消息,图像根本不显示。这是到目前为止我的代码

控制器/创建方法

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(UserAccount userAccount, HttpPostedFileBase upload)
    {
        try
        {
            if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    var photo = new UserImage
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        FileType = FileType.VesselImage,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        photo.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    userAccount.UserImages = new List<UserImage> { photo };
                }
                db.UserAccounts.Add(userAccount);
                db.SaveChanges();
                return RedirectToAction("Index");
            }//if
        }//try
        catch (RetryLimitExceededException /* dex */) 
        {
            //Log the error (uncomment dex variable name and add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }
        return View(userAccount);
    }
查看详细信息

@model Multiple_Table_Post.Models.UserAccount
@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>
<div>
<h4>UserAccount</h4>
<hr />
<dl class="dl-horizontal">
    <dt>
        @Html.DisplayNameFor(model => model.userName)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.userName)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.userLocation)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.userLocation)
    </dd>


    @if (Model.UserImages.Any(f => f.FileType == FileType.VesselImage))
    {
        <dt>
            Image
        </dt>
        <dd>
            <img src="~/File?id=@Model.UserImages.First(f => f.FileType == FileType.VesselImage).FileId" alt="avatar" />
        </dd>
    }

</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.userId }) |
@Html.ActionLink("Back to List", "Index")
</p>
谢谢,如果我错过了任何可以让这更容易的事情,请告诉我

更新:在这里,我已经包含了断点信息,关于当条件被命中时系统正在做什么,并且数据是可以看到的

试试这个:

<img src="data:image/jpg;base64,[byte array]"/>

替换:

  • jpg
    带有图像类型,即
    FileType
  • [byte array]
    使用您的字节数组,即
    内容

    如果还没有,你需要将
    内容
    转换为
    base64

    好的,我已经玩了一些,注意到我发布的更新中有一些东西。在下图中: 您会注意到文件类型列为0,但是在FileType类中,我告诉它文件类型是1

    public enum FileType
    {
        VesselImage = 1, Photo
    }
    

    因此,该条件不满足,因为它无法看到等于0的文件类型。在我的FileType类中将VesselImage更改为0可以解决此问题。:)

    我更喜欢这样做的方式是创建一个ActionResult,直接为浏览器对图像的请求提供服务。这种方法的优点之一是,如果页面多次包含图像,浏览器将自动共享资源。这样可以节省数据库点击、数据传输,并最大限度地增加缓存机会

    public ActionResult Portrait(int id)
    {
        vPhotos p = sdb.vPhotos.Where(e => e.ID == id).SingleOrDefault();
        byte[] photoArray = new byte[] { };
        return File(smallPhotoArray, "image/png");
    }
    
    现在在您看来,只需调用ActionMethod作为img src引用:

    <img src="@Url.Action("Portrait", "MyController" , new { id = id })" />
    
    
    
    我通常使用
    item.ImageLink).ToHtmlString()“/>
    (当我将图像路径存储在数据库中时)你能显示这个
    ~/File?id=…
    调用后面的代码吗?也许这个方法返回了不正确的
    内容类型
    头?
    namespace Multiple_Table_Post.Models
    {
    public enum FileType
    {
        VesselImage = 1, Photo
    }
    }
    
    <img src="data:image/jpg;base64,[byte array]"/>
    
    public enum FileType
    {
        VesselImage = 1, Photo
    }
    
    public ActionResult Portrait(int id)
    {
        vPhotos p = sdb.vPhotos.Where(e => e.ID == id).SingleOrDefault();
        byte[] photoArray = new byte[] { };
        return File(smallPhotoArray, "image/png");
    }
    
    <img src="@Url.Action("Portrait", "MyController" , new { id = id })" />