Return jpeg image from Asp.Net Core WebAPI

前端 未结 4 826
青春惊慌失措
青春惊慌失措 2020-12-08 09:30

Using asp.net core web api, I want to have my controller action method to return an jpeg image stream.
In my current implementation, b

相关标签:
4条回答
  • 2020-12-08 09:54
    [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");
            }
        }
    
    0 讨论(0)
  • 2020-12-08 09:56

    Clean solution use FilestreamResult !!

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

    Explanation:

    In ASP.NET Core you have to use the built-in File() method inside the Controller. This will allow you to manually set the content type.

    Don't create and return HttpResponseMessage, like you were used to using in ASP.NET Web API 2. It doesn't do anything, not even throwing errors!!

    0 讨论(0)
  • 2020-12-08 10:13

    In my case, I was using a relative path to the image, so the following was my working solution

    [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;
    }
    
    0 讨论(0)
  • 2020-12-08 10:15

    PhysicalFile helps to return file from Asp.Net Core WebAPI with a syntax simple

        [HttpGet]
        public IActionResult Get(int imageId)
        {            
           return PhysicalFile(@"C:\test.jpg", "image/jpeg");
        }
    
    0 讨论(0)
提交回复
热议问题