w0051977
w0051977

Reputation: 15817

Returning an image using Web API

I have a web service method, which looks like this:

[HttpGet("{id}")]
public ActionResult<byte[]> Get(Guid id)
{
    var files = Directory.GetFiles(@"Pictures\");
    foreach (var file in files)
    {
        if (file.Contains(id.ToString()))
        {
            return System.IO.File.ReadAllBytes(file);
        }
    }
    return null;
}

Here is the client code, which is definitely working i.e. it is calling the web service and the web service is returning the image:

var response2 = await client.GetAsync("http://localhost:59999/api/Images/5c60f693-bef5-e011-a485-80ee7300c692");
byte[] image2 = await response2.Content.ReadAsByteArrayAsync(); //https://stackoverflow.com/questions/39190018/how-to-get-object-using-httpclient-with-response-ok-in-web-api
System.IO.File.WriteAllBytes("image.jpg", image2);

When I try to open image.jpg in Paint; it says it is an invalid file. What is the problem?

Upvotes: 5

Views: 3753

Answers (1)

Alexander
Alexander

Reputation: 9642

If you want to return file do not return byte[] from action because it gets base64 encoded. You can decode base64 string on client or better would be using File method in action

[HttpGet("{id}")]
public ActionResult Get(Guid id)
{
    var files = Directory.GetFiles(@"Pictures\");
    foreach (var file in files)
    {
        if (file.Contains(id.ToString()))
        {
            return File(System.IO.File.ReadAllBytes(file), "image/jpeg");
        }
    }
    return null;
}

Upvotes: 5

Related Questions