我必须使用API控制器将图像从URL下载到服务器。 我不能在ASP.NET 5上使用WebClient.DownloadFile。还有其他解决方案吗?
提前致谢!
答案 0 :(得分:5)
您尚未提供任何有关WebClient不适合您的详细信息,但您也可以使用较新的HttpClient
类:
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);
}
}
答案 1 :(得分:3)
我认为这个版本有点简单:
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);
}