如何在数据库中存储图像,然后在MVC中显示它

时间:2013-01-29 13:21:57

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

如何在数据库中存储Image,然后使用MVC检索并显示它

我正在使用

MVC3
Entity Framework Database First

SQL SERVER 2008

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

Image   varbinary(MAX)  Checked

进一步使用

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

在我的映射类

当我尝试将其保存在我的创建操作方法

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

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

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

2 个答案:

答案 0 :(得分:5)

最后我做到了

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

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>

答案 1 :(得分:1)

<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>

只有这需要查看图片

相关问题