我想从某个路径获取图像,将其转换为字节并将其返回到视图以显示它。
我有一个方法,它采用图像名称/扩展名并从目录中获取图像并将其转换为字节数组,如下所示
首先我尝试将其返回为
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;
}
这是我的剃须刀视图
<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
),您还应该考虑使用ASP.NET Core中的静态文件。