ChatGPT解决这个技术问题 Extra ChatGPT

从 Asp.Net Core WebAPI 返回 jpeg 图像

使用 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;
}

https://i.stack.imgur.com/bMt50.png


h
hannes neukermans

清洁解决方案使用FilestreamResult

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

解释:

在 ASP.NET Core 中,您必须在 Controller 中使用 built-in 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 中不再显示异步警告
n
nfplee

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()。所以我猜异步部分是透明地处理的。
M
Mustafamg

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

[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;
}

J
Javier Flores
[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");
        }
    }

我不确定他们为什么不赞成这个,我所看到的只是一个工作代码