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

我有一个方法,它接受Image-Name/Extension并从目录中获取图像,然后将其转换为字节数组,如下所示

首先,我试着将其返回为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;
}

I get below response when I tested it on postman enter image description here

这是我的剃刀观点

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

最佳解决方案是将其返回为HttpResponse并在剃须刀视图中使用

推荐答案

byte[] fileBytes = new byte[fs.Length];只会创建一个相应大小的空数组,要使用这种方法,您需要复制流内容,例如:

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

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

    using MemoryStream ms = new MemoryStream();
    fs.CopyTo(ms);
    fs.Close();

    return File(ms.ToArray() , "image/png", "download.png");
}

请注意,File有一个重载接受文件的虚拟路径(即相对于应用程序,因此它不能与C:\images一起使用),您也应该考虑使用Static files in ASP.NET CorePhysicalFile.

Csharp相关问答推荐

在WPF.NET 6中使用C++/WinRT组件(但实际上是任何WinRT组件)

HttpContext. RequestAborted当Android APP失go 连接时未取消

通过条件列表删除/更新EF Core 7中的实体的有效方法

==和Tuple对象的相等<>

图形API基于appid列表检索多个应用程序

需要在重新启动ApplicartionPool或IIS后启动/唤醒API的帮助

从ASP.NET Core中的枚举字段填充 Select 选项时,将默认的第一个选项添加为 Select 元素

在swagger示例中添加默认数组列表

从另一个不同 struct 的数组创建Newtonsoft.Json.Linq.J数组

DbContext-传递自定义配置选项

如何在我的C#应用程序中设置带有reactjs前端的SignalR服务器?

如何在CSharp中将json字符串转换为DataTable?

无法使用[FromForm]发送带有图像和JSON的多部分请求

如何从Entity Framework Core中填充ListIInterface

如何从Azure函数使用Graph API(SDK 5.35)中的[FindMeetingTimes]

映射器-如何映射到多个实体

C#;AvaloniaUI;MVVM;当另一个窗口上的按钮被单击时,如何更新视图图像源?

当要删除的子模型没有父模型的1:多属性时,如何告诉实体框架设置1:1 FK条目?

读取测试项目中的应用程序设置

外部应用&&的LINQ;左外部连接&类似于PostgreSQL的查询