I have to download an image from a URL to the server with an API controller. I can't use the WebClient.DownloadFile at ASP.NET 5. Is there any other solution?
Thanks in advance!
I have to download an image from a URL to the server with an API controller. I can't use the WebClient.DownloadFile at ASP.NET 5. Is there any other solution?
Thanks in advance!
You haven't provided any details why WebClient doesn't work for you, but alternatively you could use the newer HttpClient
class:
public static async Task DownloadAsync(Uri requestUri, string filename)
{
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
using (
Stream contentStream = await (await client.SendAsync(request)).Content.ReadAsStreamAsync(),
stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None, 3145728, true))
{
await contentStream.CopyToAsync(stream);
}
}
I think this version is a little bit simpler:
using (var httpClient = new HttpClient())
using (var contentStream = await httpClient.GetStreamAsync(i.SourceUri))
using (var fileStream = new FileStream(fileUploadPath, FileMode.Create, FileAccess.Write, FileShare.None, 1048576, true))
{
await contentStream.CopyToAsync(fileStream);
}