运维开发网

异步 – 使用Xamarin Forms中的进度条下载文件

运维开发网 https://www.qedev.com 2020-07-11 10:19 出处:网络 作者:运维开发网整理
我正在尝试使用下载进度条在Xamarin Forms(PCL,因此WebClient不可用)中创建下载页面.我使用了Xamarin的以下信息,但没有成功: http://developer.xamarin.com/recipes/ios/network/web_requests/download_a_file/ http://developer.xamarin.com/recipes/cross-
我正在尝试使用下载进度条在Xamarin Forms(PCL,因此WebClient不可用)中创建下载页面.我使用了Xamarin的以下信息,但没有成功:

http://developer.xamarin.com/recipes/ios/network/web_requests/download_a_file/

http://developer.xamarin.com/recipes/cross-platform/networking/download_progress/

这是我当前的代码(带有工作进度条):

using System;
using System.Collections.Generic;

using Xamarin.Forms;
using System.Net.Http;
using System.IO;
using System.Threading.Tasks;

namespace DownloadExample
{
    public partial class DownloadPage : ContentPage
    {
        public DownloadPage ()
        {
            InitializeComponent ();

            DownloadFile("https://upload.wikimedia.org/wikipedia/commons/3/3d/LARGE_elevation.jpg");
        }

        private async Task<long> DownloadFile(string url)
        {
            long receivedBytes = 0;
            long totalBytes = 0;
            HttpClient client = new HttpClient ();

            using (var stream = await client.GetStreamAsync(url)) {
                byte[] buffer = new byte[4096];
                totalBytes = stream.Length;

                for (;;) {
                    int bytesRead = await stream.ReadAsync (buffer, 0, buffer.Length);
                    if (bytesRead == 0) {
                        await Task.Yield ();
                        break;
                    }

                    receivedBytes += bytesRead;

                    int received = unchecked((int)receivedBytes);
                    int total = unchecked((int)totalBytes);

                    double percentage = ((float) received) / total;

                    progressBar1.Progress = percentage;
                }
            }

            return receivedBytes;
        }
    }
}

现在,我需要将文件保存到本地存储.但是,在这个例子中,我没有获取文件内容,因此我无法将其写入本地存储.我需要在代码中进行哪些更改才能实现此目的?

仅供参考:在这个例子中,我正在下载一个图像,但它的特征是.pdf / .doc / .docx.

提前致谢.

BR,FG

实际上,您将文件内容复制到for循环中的缓冲区.将每次运行该循环的缓冲区内容Concat转换为新的byte [] fileContentBuffer,您可以访问可以保存在本地存储中的内容.
0

精彩评论

暂无评论...
验证码 换一张
取 消