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

3 Answers3

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
  • 21
  • 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
  • 109
  • 2
  • 9
-1

This is a simple demo UWP application for downloading an image file. Just paste the image URL link and press the download button to download the desired the image file.

MainPage.xaml

<Page
    x:Class="HttpDownloader.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HttpDownloader"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <StackPanel>
            <TextBox x:Name="uriInput"
                     Header="URI:" PlaceholderText="Please provide an uri"
                     Width="300"
                     HorizontalAlignment="Center"/>
            <Button Content="Dowload"
                    HorizontalAlignment="Center"
                    Click="Button_Click"/>
        </StackPanel>
    </Grid>
</Page>

MainPage.xaml.xs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Net.Http;
using System.Net;
using Windows.Storage.Streams;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.Graphics.Imaging;
using System.Threading;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace HttpDownloader
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            HttpClient client = new HttpClient();
            string imageUrl = uriInput.Text;
            try
            {
                using (var cancellationTokenSource = new CancellationTokenSource(50000))
                {
                    var uri = new Uri(WebUtility.HtmlDecode(imageUrl));
                    using (var response = await client.GetAsync(uri, cancellationTokenSource.Token))
                    {
                        response.EnsureSuccessStatusCode();
                        var mediaType = response.Content.Headers.ContentType.MediaType;
                        string fileName = DateTime.Now.ToString("yyyyMMddhhmmss");
                        if (mediaType.IndexOf("jpg", StringComparison.OrdinalIgnoreCase) >= 0
                            || mediaType.IndexOf("jpeg", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            fileName += ".jpg";
                        }
                        else if (mediaType.IndexOf("png", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            fileName += ".png";
                        }
                        else if (mediaType.IndexOf("gif", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            fileName += ".gif";
                        }
                        else if (mediaType.IndexOf("bmp", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            fileName += ".bmp";
                        }
                        else
                        {
                            fileName += ".png";
                        }

                        // Get the app's local folder.
                        StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

                        // Create a new subfolder in the current folder.
                        // Replace the folder if already exists.
                        string desiredName = "Images";
                        StorageFolder newFolder = await localFolder.CreateFolderAsync(desiredName, CreationCollisionOption.ReplaceExisting);
                        StorageFile newFile = await newFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                        using (Stream streamStream = await response.Content.ReadAsStreamAsync())
                        {
                            using (Stream streamToWriteTo = File.Open(newFile.Path, FileMode.Create))
                            {
                                await streamStream.CopyToAsync(streamToWriteTo);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occur");
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

You will find the image in this folder.

Users/[current user name]/AppData/Local/Packages/[Application package name]/LocalState/Images

Badhan Sen
  • 617
  • 1
  • 7
  • 18