从ViewModel显示图像

时间:2012-07-04 23:29:00

标签: sql-server asp.net-mvc-3 image viewmodel

在我的.Net MVC3应用程序中,我将一些图像存储到SQL Server数据库中(它们是.png文件)。如果可能的话,我真的很想坚持使用这种方法,因为我更喜欢使用数据库来处理文件系统(这是一个小页面,没有人会注意到性能问题)。

将图像存储到数据库似乎没问题。检索数据也不是问题。我遇到的问题是在视图中显示图像。

图像作为Varbinary(max)存储在SQL Server数据库中。视图模型使用字节[]来保存信息。视图模型中存储了其他数据,但就图像而言,这就是我所做的:

控制器:

ViewModel data = Repository.GetData();

//data now holds all of the information that I need for my view
//data.Image is of type Byte[], and it holds the image I am having trouble displaying.

return View(data);

查看

@model = data
@Html.DisplayFor(model => model.x)  @*works*@
@Html.DisplayFor(model => model.Image)  @*no good*@

是否需要将图像存储为临时文件才能使其生效? 如果是这样,似乎将图像存储在数据库中只是浪费时间。

如果我将FileStreamResult作为我的模型返回:

FileStream fs = new FileStream(path, Open, Read);
return View(new FileStreamResult(fs, "image/png"));

....我将View的模型更改为“FileStreamResult”,我仍然无法显示图像。

但是如果我像这样返回一个FileStreamResult:

FileStream fs = new FileStream(path, Open, Read);
return new FileStreamResult(fs, "image/png");

然后显示图像(但我认为这只是浏览器“打开”该文件,而不是“渲染”为html)。

我知道这个话题已经有很多问题了,但我已经看过了。我想我缺少对网络或mvc或其他东西的一些基本理解。

谢谢!

1 个答案:

答案 0 :(得分:2)

你的控制器:

    public ActionResult LoadImage(int id)
    {
        // load the image from the database and return the filestream
    }
相关问题