我正在开发一个 MVC 应用程序,我需要在浏览器中显示一个图像,但我没有实际在磁盘上的文件。
我的模型中只有一个 byte[]
数组,其中包含图像内容。是否有任何“简单”的技巧可以在 View 中显示图像而不将其写入磁盘?
我想到的第一个方法是写一个临时文件,但是:
- 我应该选择什么文件名?
- 我应该什么时候删除它?我担心我们会泄露那些文件。
所以我不想将内容写入文件。还有其他方法吗?
提前致谢。
编辑:结果页不仅是图片,我需要显示一些文字,下面是图片,例如:
<%= Response.Write("Some text here") %>
<%= /* Here my image */ %>
最佳答案
我会创建一个 Controller Action ,从字节数组返回图像。在您看来,您可以使用正常的 <img>
标签,设置 src
属性到呈现图像的 Controller 操作。
它会是这样的东西:
[HttpGet]
public ActionResult Render(...)
{
byte[] imageBytes = ...;
MemoryStream imageStream = new MemoryStream();
imageStream.Write(imageBytes, 0, imageBytes.Length);
return new FileStreamResult(imageStream, "image/png"); // might be a different mime type depending on your image type
}
然后您可以从您的 View 中执行以下操作:
<p>Some text here</p>
<img src="<%= Url.Action("Render", "MyController", new { params as needed }) %>" alt="Image" />
关于c# - 如何在浏览器中显示只有其内容的图像 (byte[]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4690574/