我从控制器中以byte数组的方式获取了一张图片,如何以最简单的方式在视图中显示它?
我从控制器中以byte数组的方式获取了一张图片,如何以最简单的方式在视图中显示它?
创建一个控制器,用于显示图片,其中包含一个Show操作,该操作从数据库中获取要显示的图像的ID。该操作应返回一个FileResult,其中包含具有适当内容类型的图像数据。
public class ImageController : Controller
{
public ActionResult Show( int id )
{
var imageData = ...get bytes from database...
return File( imageData, "image/jpg" );
}
}
根据您的视角构建图像,并使用图像id使用控制器和操作构建图像路径。
<img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>' />
Controller
派生(已经修复)。File
是 Controller
上的一个方法。 - tvanfosson使用以下方法作为最佳答案:
<img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>'
现在的MVC 4已经更新了语法,原来的语法也可以使用,但已经过时。
<img src='@Url.Action( "show", "image", new { id = ViewData["imageID"] })' />
此外,我发现当我需要这个功能时,我已经将其他数据传递给视图,因此使用模型而不是ViewData更好。
public class MyModel {
public string SomeData {get;set;}
public int FileId {get; set;}
}
来自您的控制器:
public ActionResult Index() {
MyEntity entity = fetchEntity();
MyModel model = new MyModel {
SomeData = entity.Data,
FileId = entity.SomeFile.ID
};
return View(model);
}
最后从您的角度来看:
<img src='@Url.Action("show", "image", new { id = Model.FileId })' />
对于采纳答案的控制器,“Show”方法是可行的,但我会更改硬编码的“image/jpg”以使用File.ContentType - 您可以将其与byte []一起存储,因此无需猜测用户是否正在上传自己的图像。
这里的每个答案都可能是正确的,但我认为最简单的方法是获取包含图像的字节数组或模型,然后像这样简单地添加:
<img src="data:image/jpeg;base64,@(Convert.ToBase64String(Model.Picture))">
我下载了mvc2预览版1
不必担心Microsoft.Web.Mvc的问题,因为我无法找到任何有关该问题的信息,并且花费了一个小时左右来寻找它的演变方式。
以下是我编写的代码,实现从数据库字段类型image中显示图像:
在我的控制器类(命名为store)中,我有以下代码:
public ActionResult GetImage(int id)
{
byte[] imageData = storeRepository.ReturnImage(id);
//instead of what augi wrote using the binarystreamresult this was the closest thing i found so i am assuming that this is what it evolved into
return new FileStreamResult(new System.IO.MemoryStream(imageData), "image/jpeg");
}
//in my repository class where i have all the methods for accessing data i have this
public byte[] ReturnImage(int id)
{
// i tried his way of selecting the right record and preforming the toArray method in the return statment
// but it kept giving me an error about converting linq.binary to byte[] tried a cast that didnt work so i came up with this
byte[] imageData = GetProduct(id).ProductImage.ToArray();
return imageData;
}
现在,对于我的视图页面,我尝试了这些论坛中找到的各种方法,但都不起作用。我认为它们可能已经过时了。所以,我随便尝试了最简单的方法,结果完美解决了问题。
<image src='/store/getimage/<%= Html.Encode(Model.productID) %>' alt="" />
public ActionResult EmployeeImage(int id)
{
byte[] imageData ="Retrieve your Byte[] data from database";
if (imageData!= null && imageData.Length > 0)
{
return new FileStreamResult(new System.IO.MemoryStream(imageData), "image/jpeg");
}
}
Byte[] bytes = (Byte[])dr["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dr["Image/JPEG"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();