posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

带进度 http://t.zoukankan.com/h82258652-p-10950580.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
namespace AppUtils
{
    public struct HttpDownloadProgress
    {
        public long BytesReceived { get; set; }
        public long TotalBytesToReceive { get; set; }
    }
    public static class HttpClientExtensions
    {
        private const int BufferSize = 8192;
 
        public static async Task<byte[]> GetByteArrayAsync(this HttpClient client, Uri requestUri, IProgress<HttpDownloadProgress> progress, CancellationToken cancellationToken)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }
 
            using (var responseMessage = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))
            {
                if (responseMessage.StatusCode== System.Net.HttpStatusCode.NotFound)
                {
                    throw new Exception(System.Net.HttpStatusCode.NotFound.ToString());
                }
                responseMessage.EnsureSuccessStatusCode();
 
                var content = responseMessage.Content;
                if (content == null)
                {
                    return Array.Empty<byte>();
                }
 
                var headers = content.Headers;
                var contentLength = headers.ContentLength;
                using (var responseStream = await content.ReadAsStreamAsync().ConfigureAwait(false))
                {
                    var buffer = new byte[BufferSize];
                    int bytesRead;
                    var bytes = new List<byte>();
 
                    var downloadProgress = new HttpDownloadProgress();
                    if (contentLength.HasValue)
                    {
                        downloadProgress.TotalBytesToReceive = contentLength.Value;
                    }
                    progress?.Report(downloadProgress);
                    while ((bytesRead = await responseStream.ReadAsync(buffer, 0, BufferSize, cancellationToken).ConfigureAwait(false)) > 0)
                    {
                        bytes.AddRange(buffer.Take(bytesRead));
 
                        downloadProgress.BytesReceived += bytesRead;
                        progress?.Report(downloadProgress);
                    }
 
                    return bytes.ToArray();
                }
            }
        }
    }
}

  UpgradeService:System.Net.Http.HttpClient _client = new HttpClient();

1
2
3
4
5
6
7
8
9
10
11
12
public async Task DownloadFileAsync(string url, IProgress<HttpDownloadProgress> progress, CancellationToken token)
        {
            var filePath = "D:\test.txt";
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
 
            var bytes = await _client.GetByteArrayAsync(new Uri(url), progress, token);
            using var fileStream = new FileStream(filePath, FileMode.Create);
            fileStream.Write(bytes, 0, bytes.Length);
        }

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
string fileUrl = "http://xxxxx/test.txt";
            CancellationTokenSource CTSource = new CancellationTokenSource();
            //当前线程
            var progress = new Progress<HttpDownloadProgress>(async percent =>
            {
                BytesReceived = percent.BytesReceived / 1024; //当前已经下载的Kb
                TotalBytesToReceive = percent.TotalBytesToReceive / 1024; //文件总大小Kb
                DownloadMsg = "正在下载: " + BytesReceived + "KB / " + TotalBytesToReceive + "KB";
                //StateHasChanged();
 
                //await moduleJS.InvokeVoidAsync("SetDownloadMsg", DownloadMsg);
 
            });
            await _UpgradeService.DownloadFileAsync(fileUrl, progress, CTSource.Token);


旧代码:

复制代码
#region 下载文件
    /// <summary>
    /// Http方式下载文件
    /// </summary>
    /// <param name="url">http地址</param>
    /// <param name="localfile">本地文件</param>
    /// <returns></returns>
    public bool Download(string url, string localfile)
    {
        bool flag = false;
        long startPosition = 0; // 上次下载的文件起始位置
        FileStream writeStream; // 写入本地文件流对象

        long remoteFileLength = GetHttpLength(url);// 取得远程文件长度
        System.Console.WriteLine("remoteFileLength=" + remoteFileLength);
        if (remoteFileLength == 745)
        {
            System.Console.WriteLine("远程文件不存在.");
            return false;
        }

        // 判断要下载的文件夹是否存在
        if (File.Exists(localfile))
        {

            writeStream = File.OpenWrite(localfile);             // 存在则打开要下载的文件
            startPosition = writeStream.Length;                  // 获取已经下载的长度

            if (startPosition >= remoteFileLength)
            {
                System.Console.WriteLine("本地文件长度" + startPosition + "已经大于等于远程文件长度" + remoteFileLength);
                writeStream.Close();

                return false;
            }
            else
            {
                writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
            }
        }
        else
        {
            writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
            startPosition = 0;
        }


        try
        {
            HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接

            if (startPosition > 0)
            {
                myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
            }


            Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流


            byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
            int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次

            long currPostion = startPosition;

            while (contentSize > 0)// 如果读取长度大于零则继续读
            {
                currPostion += contentSize;
                int percent = (int)(currPostion * 100 / remoteFileLength);
                System.Console.WriteLine("percent=" + percent + "%");

                writeStream.Write(btArray, 0, contentSize);// 写入本地文件
                contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
            }

            //关闭流
            writeStream.Close();
            readStream.Close();

            flag = true;        //返回true下载成功
        }
        catch (Exception)
        {
            writeStream.Close();
            flag = false;       //返回false下载失败
        }

        return flag;
    }

    // 从文件头得到远程文件的长度
    private static long GetHttpLength(string url)
    {
        long length = 0;

        try
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

            if (rsp.StatusCode == HttpStatusCode.OK)
            {
                length = rsp.ContentLength;// 从文件头得到远程文件的长度
            }

            rsp.Close();
            return length;
        }
        catch (Exception e)
        {
            return length;
        }

    }
    #endregion
复制代码

 

posted on   邢帅杰  阅读(149)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示