【问题标题】:Return jpeg image from Asp.Net Core WebAPI从 Asp.Net Core WebAPI 返回 jpeg 图像
【发布时间】:2017-04-09 05:20:10
【问题描述】:

使用 asp.net core web api,我想让我的控制器操作方法返回一个 jpeg 图像流
在我当前的实现中,浏览器只显示一个 json 字符串。 我的期望是在浏览器中看到图像。

使用chrome开发者工具调试的时候发现内容类型还是

Content-Type:application/json; charset=utf-8

在响应标头中返回,即使在我的代码中我手动将内容类型设置为“image/jpeg”。

寻找解决方案我的 Web API 如下

[HttpGet]
public async Task<HttpResponseMessage> Get()
{
    var image = System.IO.File.OpenRead("C:\\test\random_image.jpeg");
    var stream = new MemoryStream();

    image.CopyTo(stream);
    stream.Position = 0;            
    result.Content = new StreamContent(image);
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = "random_image.jpeg";
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
    result.Content.Headers.ContentLength = stream.Length;

    return result;
}

【问题讨论】:

    标签: asp.net-core content-type asp.net-core-webapi


    【解决方案1】:

    干净的解决方案使用FilestreamResult!!

    [HttpGet]
    public IActionResult Get()
    {
        var image = System.IO.File.OpenRead("C:\\test\\random_image.jpeg");
        return File(image, "image/jpeg");
    }
    

    解释:

    在 ASP.NET Core 中,您必须在控制器中使用 内置 File() 方法。这将允许您手动设置内容类型。

    不要创建并返回HttpResponseMessage,就像你习惯在 ASP.NET Web API 2 中使用的那样。它什么都不做,甚至不会抛出错误!!

    【讨论】:

    • Visual Studio 说这个方法缺少 await 用法,因此会同步运行。是否可以缓存文件以便不必每次都读取它?为什么不使用接受文件路径而不是读取文件的重载 File 方法呢?如果读取文件,为什么不使用using 语句?
    • 将这一行写成: return await Task.Run(() => File(image, "image/jpeg"));为我删除了错误并且也有效。
    • 将方法从 'async Task' 重写为 'IActionResult' 也能以更简洁的方式实现这一点(Visual Studio 正确地指出此方法中存在异步行为);) ...
    • 不要忘记 Dispose 那个 OpenRead 对象,但是 PhysicalFile 是一个更好的解决方案。
    • 更改了代码,以便在 vs @DotBert 中不再显示异步警告
    【解决方案2】:

    PhysicalFile 帮助从 Asp.Net Core WebAPI 返回文件,语法简单

        [HttpGet]
        public IActionResult Get(int imageId)
        {            
           return PhysicalFile(@"C:\test.jpg", "image/jpeg");
        }
    

    【讨论】:

    • 我想知道这是异步的吗?我不想参与死锁或无法访问的文件?
    • @ASLIM 方法 PhysicalFile() 返回一个 PhysicalFileResult 类型的实例,它支持异步执行。因此,如果我理解正确,ASP.NET 基础架构将选择该异步方法,该方法反过来将调用 PhysicalFileResultExecutor.ExecuteAsync() -> response.SendFileAsync()。所以我猜异步部分是透明处理的。
    【解决方案3】:

    就我而言,我使用的是图像的相对路径,所以以下是我的工作解决方案

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var url = "/content/image.png";
        var path = GetPhysicalPathFromURelativeUrl(url);
        return PhysicalFile(image, "image/png");
    }
    public string GetPhysicalPathFromRelativeUrl(string url)
    {            
        var path = Path.Combine(_host.Value.WebRootPath, url.TrimStart('/').Replace("/", "\\"));
        return path;
    }
    

    【讨论】:

      【解决方案4】:
      [HttpGet("Image/{id}")]
          public IActionResult Image(int id)
          {
              if(id == null){ return NotFound(); }
              else{
      
                  byte[] imagen = "@C:\\test\random_image.jpeg";
                  return File(imagen, "image/jpeg");
              }
          }
      

      【讨论】:

      • 我不知道他们为什么不赞成这个,我看到的只是一个工作代码
      猜你喜欢
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多