Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

content type - Return jpeg image from Asp.Net Core WebAPI

Using asp.net core web api, I want to have my controller action method to return an jpeg image stream.
In my current implementation, browser displays only a json string. My expectation is to see the image in the browser.

While debugging using chrome developer tools I found that the content type is still

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

returned in the response header, even though in my code I manually set the content type to "image/jpeg".

Looking for a solution My Web API is as below

[HttpGet]
public async Task<HttpResponseMessage> Get()
{
    var image = System.IO.File.OpenRead("C:\test
andom_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;
}

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Clean solution use FilestreamResult !!

[HttpGet]
public 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!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...