在asp.net mvc中显示图像
本文关键字:显示 显示图 图像 mvc asp net | 更新日期: 2023-09-27 18:16:00
我正在尝试创建一个网站来上传/显示图像(使用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; }
}
//控制器
private PhotoDBContext db = new PhotoDBContext();
public ActionResult Index()
{
return View(db.Photos.ToList());
}
//查看
@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>
此外,如果我将图像保存为字节数组(而不是物理存储文件并使用文件路径(,我如何重新创建图像并在视图中显示它。即,在视图中迭代模型的同时,如何从字节数组重新创建图像?
编辑
我已经能够通过以下操作解决显示问题(两者都需要(-1( 将路径更改为相对路径2( 已将图像移动到App_Data以外的单独文件夹中。(找到这个(
谢谢。
确保您的图像是一个相对路径,例如:
@Url.Content("~/Content/images/myimage.png")
MVC4
<img src="~/Content/images/myimage.png" />
您可以随时将byte[]
转换为Base64
string
。
string base64String = Convert.ToBase64String(imageBytes);
<img src="@String.Format("data:image/png;base64,{0}", base64string)" />
即使在MVC4中,也可以使用处理程序来执行此操作。下面是我之前做的一个例子:
public class ImageHandler : IHttpHandler
{
byte[] bytes;
public void ProcessRequest(HttpContext context)
{
int param;
if (int.TryParse(context.Request.QueryString["id"], out param))
{
using (var db = new MusicLibContext())
{
if (param == -1)
{
bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));
context.Response.ContentType = "image/png";
}
else
{
var data = (from x in db.Images
where x.ImageID == (short)param
select x).FirstOrDefault();
bytes = data.ImageData;
context.Response.ContentType = "image/" + data.ImageFileType;
}
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
}
else
{
//image not found
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
在视图中,我将照片的ID添加到处理程序的查询字符串中。