c# - 返回字节数组作为具有 Image/png 内容类型的 Http 响应

标签 c# asp.net-mvc asp.net-core asp.net-web-api httpresponse

我想从某个路径获取图像,将其转换为字节并将其返回到 View 以显示它。

我有一个方法,它采用图像名称/扩展名并从目录中获取图像并将其转换为字节数组,如下所示

首先,我尝试将其作为 File 返回,如下所示

public IActionResult getImage(string image)
{
   var fullPath = Path.Combine("C:\\images\\", image);

   FileStream fs = new FileStream(fullPath, FileMode.Open);

   byte[] fileBytes = new byte[fs.Length];
   fs.Close();

   return File(fileBytes , "image/png");
}

这对我不起作用,因为它在 Webroot 中查找图像,例如“Image/Image-name.png”

然后我尝试通过 HttpResponseMessage 编写它,如下所示

public HttpResponseMessage getImage(string image)
{
   var fullPath = Path.Combine("C:\\images\\", image);

   FileStream fs = new FileStream(fullPath, FileMode.Open);

   byte[] fileBytes = new byte[fs.Length];
   fs.Close();

   HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
   result.Content = new ByteArrayContent(fileBytes);
   result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");

   return result;
}

当我在 postman 上测试它时,我得到以下响应 enter image description here

这是我的 Razor View

 <img src="@Url.Action("getImage", "Image", new{ image=Model.Image})" />

最佳解决方案是将其作为 HttpResponse 返回并在 razor View 中使用它

最佳答案

您可以删除代码并高效地完成任务😁:

public IActionResult getImage(string image)
{
   var fullPath = Path.Combine("C:\\images\\", image);

   return PhysicalFile(fullPath, "image/png");
}

关于c# - 返回字节数组作为具有 Image/png 内容类型的 Http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76762101/

相关文章:

c# - 在单独的项目中共享 javascript 文件

asp.net-core - NSwag - 我如何添加评论?

具有静态属性或方法的 C# 接口(interface)?

c# - 使用 ViewState 时出现异常

.net - 替换字符串中的空格,mvc razor

asp.net-mvc - 什么时候应该在 asp.net mvc 2 中使用异步 Controller ?

asp.net-mvc - 获取记录时出错 "LINQ to Entities does not recognize the method"

c# - 在 C# 中延迟任务 - 释放数据库上下文

.net - .Net Core项目中Nuget和SDK依赖项之间的区别

c# - 使用 Microsoft Visual Web Developer 2010 Express 的 Web.Config 中无法识别的配置部分 httpHandlers