【问题标题】:How to Store an Image in Database and then Display it in MVC如何将图像存储在数据库中,然后在 MVC 中显示
【发布时间】:2013-01-29 13:21:56
【问题描述】:

如何将图像存储在数据库中,然后使用 MVC 检索和显示它

我正在使用 MVC3、Entity Framework Database First 和 SQL SERVER 2008

在数据库中,我使用 varbinary(MAX) 作为图像

Image   varbinary(MAX)  Checked

我进一步使用

[DisplayName("Image")]
    public byte[] Image { get; set; }

在我的映射类中

当我尝试将其保存在我的 Create 操作方法中时

public ActionResult Create(MarjaaModel newMarjaa, HttpPostedFileBase uploadFile)
    {
        if (uploadFile != null && uploadFile.ContentLength > 0)
        {                               
            newMarjaa.Image = new byte[uploadFile.ContentLength];
            uploadFile.InputStream.Read(newMarjaa.Image, 0, uploadFile.ContentLength);
        }
        try
        {
            data.submitMarjaa(newMarjaa);
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

我成功将图片保存为二进制数据

但请告诉我如何检索此图像并将其显示在我的视图中

【问题讨论】:

  • 是的,有可能。你还有什么想问的吗?如果没有,您可能希望显示使用 what you have tried so far 并解释您在代码中遇到了什么困难。否则我真的不明白我们怎么能在这里进行任何建设性的讨论。
  • 有可能,但为什么要将图像存储在数据库中?将照片的链接存储在数据库中,并将照片存储在目录中。
  • @War10ck ,亲爱的,我想将图像存储在数据库中
  • Com'on 所谓的天才知识分子所做的不仅仅是反对投票。虽然我不在乎

标签: asp.net-mvc-3 sql-server-2008 entity-framework-5


【解决方案1】:

我终于做到了

我的控制器中的一个简单方法

public ActionResult ShowImage(long id)
    {
        var model = data.getMarjaa(id);
        return File(model.Image, "image/jpg");
    }

在我看来

<td>
       @if (item.Image == null)
       {
       <img width="40" height="40" src="http://www.abc.com/images/staff/no_worry[1].jpg" />
       }
       else
       {
       <img width="40" height="40" src='@Url.Action("ShowImage", "Admin", new { id = item.id })' />
       }
    </td>

【讨论】:

    【解决方案2】:
    <td>
                   @{
                       var base64 = Convert.ToBase64String(item.NewsImage);
                       var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
    
                }
                <img src='@imgsrc' style="max-width:100px;max-height:100px" />
                </td>
    

    只有这个需要查看图片

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      • 2015-09-08
      • 2011-12-28
      • 1970-01-01
      相关资源
      最近更新 更多