我想从某个路径获取图像,将其转换为字节,并将其返回到视图以显示它.
我有一个方法,它接受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
这是我的剃刀观点
<img src="@Url.Action("getImage", "Image", new{ image=Model.Image})" />
最佳解决方案是将其返回为HttpResponse
并在剃须刀视图中使用