从url下载图像并不总是保存整个图像(Winrt)

本文关键字:图像 保存 Winrt 下载 url | 更新日期: 2023-09-27 18:03:24

我使用以下代码从url

下载图像
HttpClient client = new HttpClient();
        var stream = await client.GetStreamAsync(new Uri("<your url>"));
        var file = await KnownFolders.PictureLibrary.CreateFileAsync("myfile.png");
        using (var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            using (stream)
                await stream.CopyToAsync(targetStream.AsStreamForWrite());
        }

一些用户报告说,它并不总是下载整个图像。他们有时得到部分图像,其余的只是垃圾。

这有什么原因吗?谢谢!

从url下载图像并不总是保存整个图像(Winrt)

我建议尝试WebClient类与DownloadData或DownloadDataAsync方法。

File.WriteAllBytes("myfile.png",
    new WebClient().DownloadData("<your url>"));

edit如果流给您带来麻烦,您可以使用字节数组响应代替。你的"using"语句内的异步代码可能会导致它提前处置,也许?

var httpClient = new HttpClient();
var data = await httpClient.GetByteArrayAsync(new Uri("<Your URI>"));
var file = await KnownFolders.PictureLibrary.CreateFileAsync("myfile.png");
var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite)
await targetStream.AsStreamForWrite().WriteAsync(data, 0, data.Length);
targetStream.FlushAsync().Wait();
targetStream.Close();

BackgroundDownloader是下载文件最简单的方法。

using Windows.Storage;
public async Task DownloadPhoto(Uri uri)
{
    var folder = ApplicationData.Current.LocalFolder;
    var photoFile = await folder.CreateFileAsync("photo.jpg", CreationCollisionOption.ReplaceExisting);
    var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
    var dl = downloader.CreateDownload(uri, photoFile);
    await dl.StartAsync();
}

如果你使用HttpClient,那么如果你的图像大于64K,它会出错。您必须设置httpClient。MaxResponseContentBufferSize设置为更大的值

请参阅MSDN快速入门,他们将最大缓冲区大小设置为256K。http://msdn.microsoft.com/en-us/library/windows/apps/xaml/JJ152726 (v = win.10) . aspx

我个人使用BackgroundDownloader