我正在从控制器获取字节数组格式的图像,如何在视图中显示它?以最简单的方式。
发布于 2009-05-19 01:08:00
使用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"] } ) %>' />
发布于 2013-12-25 16:22:17
使用这个的公认答案是:
<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“方法可以接受答案,但我会将硬编码的”File.ContentType /jpg“改为使用byte[] -你可以将其与jpg一起存储,这样你就不需要猜测用户是否上传了他们自己的图像。
发布于 2019-03-15 14:32:46
这里的每个答案都可能是正确的,但我认为最简单的方法是获取包含图像的字节数组或模型,然后像这样简单地添加
<img src="data:image/jpeg;base64,@(Convert.ToBase64String(Model.Picture))">
https://stackoverflow.com/questions/880515
复制相似问题