在asp.net mvc中显示图像

sid*_*rth 18 c# asp.net-mvc-4

我正在尝试创建一个上传/显示图像的网站(使用MVC4).我编写了以下代码来获取本地存储在服务器下App_Data\Images文件夹下的图像.图像的路径存储在模型的ImageFile属性中.

视图呈现ID,各种图像的标题,但未加载图像.映像文件存在于针对ImageFile属性存储的路径中.我怎样才能解决这个问题?

//模型

public class Photo
{
    public int ID { get; set; }

    public string ImageFile { get; set; } //This contains a path where the image is locally stored on the server
    public string Caption { get; set; }
byte[] Image { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

//控制器

private PhotoDBContext db = new PhotoDBContext();

public ActionResult Index()
{
    return View(db.Photos.ToList());
}
Run Code Online (Sandbox Code Playgroud)

//视图

@model IEnumerable<MyPhotoLibrary.Models.Photo>

<table>
 @foreach (var item in Model) {
 <tr>
    <td>
        <img src="@Url.Content(item.ImageFile)" alt="" />
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Caption)
    </td>
 </tr>
 }
</table>
Run Code Online (Sandbox Code Playgroud)

此外,如果我将图像保存为字节数组(而不是物理存储文件并使用文件路径),我该如何重新创建图像并在视图中显示它.即,如何在视图中迭代模型时从字节数组重新创建图像?

编辑

我已经能够通过执行以下操作解决显示问题(两者都需要) - 1)将路径更改为相对路径2)将图像移动到App_Data以外的单独文件夹.(发现这个)

谢谢.

Gab*_*abe 33

确保您的图像是相对路径,例如:

@Url.Content("~/Content/images/myimage.png")
Run Code Online (Sandbox Code Playgroud)

MVC4

<img src="~/Content/images/myimage.png" />
Run Code Online (Sandbox Code Playgroud)

您可以将其byte[]转换为动态Base64 string.

string base64String = Convert.ToBase64String(imageBytes);

<img src="@String.Format("data:image/png;base64,{0}", base64string)" />
Run Code Online (Sandbox Code Playgroud)

  • 实际上,在MVC 4(更具体地说是Razor 2)中,你不需要`Url.Content`,你可以做`<img rel="nofollow noreferrer" src ="〜/ Content/images/myimage.png"/>` (2认同)