我已经将图像存储为字节数组,现在我需要从字节数组中将其显示回来。所以我有一个 <img>
标记,并且我已在运行时将该标记的源分配给将获取图像的方法。
查看:
document.getElementById("Logo").setAttribute("src",'@Url.Action("GetImage","AdminLogoManager", new { id = Model.Asset.AssetID})');
<img id="Logo" />
Controller 中的代码:
private List<LogoModel> LogoModelList
{
get
{
var logoModelList = GetLogoModelListFromSomewhere();
return logoModelList;
}
}
}
public FileContentResult GetImage(int id)
{
LogoModel m = LogoModelList.Find(p => p.Asset.AssetID == id);
return new FileContentResult(m.Asset.Document, "image/jpeg");
}
但它不显示图像。我检查了 Chrome 调试器,它说: 服务器响应错误 500(内部服务器错误) 任何人都可以帮助我让它工作吗?我知道 LogoModelList 不是 null 或空的,而且 ID 可能是正确的
PS:它甚至没有调试。我无法在 GetImage()
上设置调试点
最佳答案
令我困扰的是,我无法找到我在此处添加的代码的原始来源,但它确实有效。如果有人有原始链接,请随时告诉我或编辑此答案(如果您的声誉允许):
helper :
public static class ImageResultHelper
{
public static ImageResult Image( this Controller controller, byte[] imageData, string mimeType )
{
return new ImageResult()
{
ImageData = imageData,
MimeType = mimeType
};
}
public static ImageResult Image( this Controller controller, byte[] imageData, string mimeType, HttpCacheability cacheability, DateTime expires, string eTag )
{
return new ImageResult()
{
ImageData = imageData,
MimeType = mimeType,
Cacheability = cacheability,
Expires = expires,
ETag = eTag
};
}
}
和自定义ActionResult
:
public class ImageResult : ActionResult
{
public ImageResult()
{
}
public byte[] ImageData { get; set; }
public string MimeType { get; set; }
public HttpCacheability Cacheability { get; set; }
public string ETag { get; set; }
public DateTime? Expires { get; set; }
public override void ExecuteResult( ControllerContext context )
{
if ( this.ImageData == null )
{
throw new ArgumentNullException( "ImageData" );
}
if ( string.IsNullOrEmpty( this.MimeType ) )
{
throw new ArgumentNullException( "MimeType" );
}
context.HttpContext.Response.ContentType = this.MimeType;
if ( !string.IsNullOrEmpty( this.ETag ) )
{
context.HttpContext.Response.Cache.SetETag( this.ETag );
}
if ( this.Expires.HasValue )
{
context.HttpContext.Response.Cache.SetCacheability( this.Cacheability );
context.HttpContext.Response.Cache.SetExpires( this.Expires.Value );
}
context.HttpContext.Response.OutputStream.Write( this.ImageData, 0, this.ImageData.Length );
}
}
关于javascript - 在 MVC3 中将字节数组显示为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11841335/