5

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?

6
  • The image picked up by the webervice, are you sure this is a jpg? Commented Mar 16, 2019 at 16:04
  • @D.J, I am certain. I just checked. Commented Mar 16, 2019 at 16:05
  • ok, can you check if the bytearray received by the client is as long as the one send from the webservice ? maybe the image is not fully sent to the client Commented Mar 16, 2019 at 16:08
  • @D.J, the sizes of the byte arrays are different. There is something wrong. How do I get the image from the response? I cannot believe how difficult this is. Commented Mar 16, 2019 at 16:10
  • my first guess would be that the client doesn't receive the image but an error or info page, can you open url that is requested by the client in a browser ? Commented Mar 16, 2019 at 16:13

1 Answer 1

5

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@w0051977 with this answer client should be unchanged. Try it out
Are you saying use the client code in my original post? Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.