Using Windows.Web.Http.HttpClient
how can I download an image? I would like use this HttpClient because it is available to use in portable class libraries.
HttpClient is a modern HTTP client for . NET applications. It can be used to consume functionality exposed over HTTP. For example, a functionality exposed by an ASP.NET Web API can be consumed in a desktop application using HttpClient.
Why Do We Need HttpClient? The front-end of applications communicate with back-end services to get or send the data over HTTP protocol using either XMLHttpRequest interface or fetch API . This communication is done in Angular with the help of HttpClient .
public async void downLoadImage(string url)
{
using (var client = new HttpClient())
{
var response = client.GetAsync(url).Result;
BitmapImage bitmap = new BitmapImage();
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
using (var stream = await response.Content.ReadAsStreamAsync())
{
using (var memStream = new MemoryStream())
{
await stream.CopyToAsync(memStream);
memStream.Position = 0;
bitmap.SetSource(memStream.AsRandomAccessStream());
}
}
HardcodedValues.profilePic = bitmap;
}
}
}
In .net core web api you can use the below code
[Route("getProductImage/v1")]
[HttpGet]
public async Task<IActionResult> getProductImage(GetProductImageQueryParam parammodel)
{
using (HttpClient client = new HttpClient())
{
MNimg_URL = MNimg_URL + parammodel.modelname;
HttpResponseMessage response = await client.GetAsync(MNimg_URL);
byte[] content = await response.Content.ReadAsByteArrayAsync();
//return "data:image/png;base64," + Convert.ToBase64String(content);
return File(content, "image/png", parammodel.modelname);
}
}
here GetProductImageQueryParam is a class with input parameters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With