从url下载映像到服务器以在asp.net 5 api中处理

时间:2015-12-19 14:06:21

标签: asp.net asp.net-web-api asp.net-core

我必须使用API​​控制器将图像从URL下载到服务器。 我不能在ASP.NET 5上使用WebClient.DownloadFile。还有其他解决方案吗?

提前致谢!

2 个答案:

答案 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); 
}