如何使用Web API Get方法返回图像

J.D*_*.D. 26 c# asp.net-web-api asp.net-core

我需要使用Web API Get方法返回一个图像.下面的代码似乎工作正常,除了我在Fiddler的ImageView窗口中收到此消息,"此响应已编码,但并未声称是图像."

public HttpResponseMessage Get()
{
    using (FileStream fs = new FileStream(filePath, FileMode.Open))
    {
        HttpResponseMessage response = new HttpResponseMessage(); 
        response.Content = new StreamContent(fs);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        return response;
    }
} 
Run Code Online (Sandbox Code Playgroud)

我在Fiddler中也看到了与此代码相同的结果:

public HttpResponseMessage Get()
{
    HttpResponseMessage response = new HttpResponseMessage();
    Byte[] b = (GetImageByteArray());
    response.Content = new ByteArrayContent(b);
    response.Content.LoadIntoBufferAsync(b.Length).Wait();
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
    return response;
}
Run Code Online (Sandbox Code Playgroud)

如果我使用.png格式,我会得到相同的结果.

感谢您的帮助,

dot*_*tep 36

如果我理解正确,那么你要求具体到asp.net核心.在ASP.net核心中,HttpResponseMessage不是像我们以前在ASP.net web api 2中那样返回结果的方法.

在asp.net核心(WEB API)中,只是看起来像这样.

[HttpGet]
public IActionResult Get()
{            
    Byte[] b = System.IO.File.ReadAllBytes(@"E:\\Test.jpg");   // You can use your own method over here.         
    return File(b, "image/jpeg");
}
Run Code Online (Sandbox Code Playgroud)

注意:正如您在Fiddler Imageview中提到的那样,您会看到这样的消息"他的响应已编码,但并未声称是图像." 因为ASP.net核心将HttpResponseMessage视为简单类并转换为json或xml.

  • 最好使用接受流的`File`方法重载,这样在发送之前不要将图片加载到服务器内存中.`FileStream stream = File.Open(@"E:\\ Test.jpg"); return File(stream,"image/jpeg");`甚至更容易:`返回PhysicalFile("@ E:\\ Test.jpg","image/jpg");`https://github.com/aspnet/ MVC/BLOB的/ dev/src目录/ Microsoft.AspNetCore.Mvc.Core/ControllerBase.cs#L711 (5认同)

Mar*_*ark 12

添加这个答案是因为这些评论很容易被错过(就像我几乎做的那样)。

Jussi Palo 建议(使用 PhysicalFileResult):

[HttpGet]
public IActionResult Get()
{        
    return PhysicalFile(@"E:\\Test.jpg", "image/jpeg");
}
Run Code Online (Sandbox Code Playgroud)
  • 一个很好的单衬管,可以处理 206 部分之类的事情。

Tseng 建议(使用接受流的 FileContentResult 构造函数的重载):

[HttpGet]
public IActionResult Get()
{        
    FileStream stream = File.Open(@"E:\\Test.jpg");
    return File(stream, "image/jpeg");
}
Run Code Online (Sandbox Code Playgroud)
  • 如果您的流来自其他地方(例如嵌入式资源),则很有用。

对于 RL,请记住检查文件/资源​​是否存在,如果不存在则返回 404。


Hie*_*yen 9

This is the way I get image from API in my project. I share for whom concern.

Image content save to Images folder in server and image name saved to Database.

[Route("api/dashboard/GetImage")]
public byte[] GetImage(int componentId)
{
            using (var dashboardService = new DashboardService())
            {
                var component = dashboardService.GetImage(componentId);
                var context = HttpContext.Current;
                string filePath = context.Server.MapPath("~/Images/" + component.ImageName);
                context.Response.ContentType = "image/jpeg";
                using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        fileStream.CopyTo(memoryStream);
                        Bitmap image = new Bitmap(1, 1);
                        image.Save(memoryStream, ImageFormat.Jpeg);

                        byte[] byteImage = memoryStream.ToArray();
                        return byteImage;
                    }
                }
            }
}
Run Code Online (Sandbox Code Playgroud)

Get image content in Angular

this.dashboardService.getImage(this.componentId)
    .subscribe((blob: any) => {
      let objectURL = 'data:image/jpeg;base64,' + blob;
      this.imageUrl = this.sanitizer.bypassSecurityTrustUrl(objectURL);;
});
Run Code Online (Sandbox Code Playgroud)