0

I need help retrieving a picture from a web service. It's a GET request.

At the moment I am retrieving a response and I am able to convert it to a byte array, which is what I am going for, but the byte array crashes the app, so I don't think the content is set right.

I have tried to set the response content with:

response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };     

Even though my guess is that it is set incorrectly, or it is up in the requestHeader it is set wrong.

Any ideas?

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(baseurl.uri);
    client.DefaultRequestHeaders.Add("x-access-token", sessionToken);
    client.DefaultRequestHeaders
          .Accept
          .Add(new MediaTypeWithQualityHeaderValue("image/jpeg")
            );

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "");
    try
    {
        Task<HttpResponseMessage> getResponse = client.SendAsync(request);
        HttpResponseMessage response = new HttpResponseMessage();
        response = await getResponse;           
         //1. response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };
        //2. response.Content.Headers.ContentType =

       //new MediaTypeHeaderValue("image/jpeg");//("application/octet-stream");


        byte[] mybytearray = null;
        if (response.IsSuccessStatusCode)
        {
        //3.
            mybytearray = response.Content.ReadAsByteArrayAsync().Result;
        }

        var responseJsonString = await response.Content.ReadAsStringAsync();
        System.Diagnostics.Debug.WriteLine(responseJsonString);
        System.Diagnostics.Debug.WriteLine("GetReportImage ReponseCode: " + response.StatusCode);
        return mybytearray;//{byte[5893197]}
    }
    catch (Exception ex)
    {
        string message = ex.Message;
        return null;
    }
}
ako89
  • 57
  • 2
  • 11
  • 2
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Andrew Morton Sep 21 '17 at 09:54
  • What line is throwing the exception? – mjwills Sep 21 '17 at 10:04
  • `response.Content.Headers.ContentDisposition` is a header that the _server_ can set, not the client. Trying to set it in your downloaded response object after the fact is nonsensical. Your client has already processed the response and observed the headers sent by the server. Setting another header now is meaningless. – ADyson Sep 21 '17 at 10:40
  • ADyson You are right i am probably not supposed to correct the response like that. I can see that the reponse.Content.Headers is: {Content-Type: text/plain Content-disposition: attachment; filename="hello2.jpg"} – ako89 Sep 21 '17 at 11:26

2 Answers2

0

You can send the valid byte array of the image as part of the HttpContent

 HttpContent contentPost = new 
    StringContent(JsonConvert.SerializeObject(YourByteArray), Encoding.UTF8,
    "application/json");

After deserializing your result you can retrieve your byte array save the same as jpeg or any other format.

byte[] imageByteArray = byteArray;

using(Image image = Image.FromStream(new MemoryStream(imageByteArray)))
{
    image.Save("NewImage.jpg", ImageFormat.Jpeg); 
}
waris kantroo
  • 83
  • 3
  • 20
  • Something is still wrong when i convert the byte array to the Image. So I am trying to find out if there is another way to verify what i am getting send – ako89 Sep 21 '17 at 11:40
  • byte array has to be a valid byte array of image. Are you sending a valid byte array in your HttpContent – waris kantroo Sep 22 '17 at 14:54
  • after deserializing your result from the web api you would able to do that bu running one below `response.Content.ReadAsStringAsync();` – waris kantroo Sep 22 '17 at 18:29
0

You can get picture as any other type of file if you do not need to validate the file

using var httpClient = new HttpClient();
var streamGot = await httpClient.GetStreamAsync("domain/image.png");
await using var fileStream = new FileStream("image.png", FileMode.Create, FileAccess.Write);
streamGot.CopyTo(fileStream);
NewTom
  • 79
  • 1
  • 7