HttpClient获取图片并保存到本地

1. FileDownLoad.cs

本次测试使用HttpClient从网站下载图片并保存到本地,在FileDownLoad类中提供DownLoadInBackGround接口,供外部调用,封装具体的下载操作。

using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace CSProject
{
    public delegate void DownLoadMethodInvoker(bool ret, string URL, string fullfilename);
    //处理下载回调,后期可以作为下载接口的外部参数,提供给外部调用者处理下载后的操作
    public class FileDownLoad
    {
        private static string PATH = "E:/VSWorkspace/CSharp/CSProject/CSProject/Data/Images/";//本地地址
        private static FileDownLoad instance = null;
        private static HttpClient httpClient = null;
        private static HttpClientHandler httpClientHandler = null;
        public static FileDownLoad Instance
        {
            get
            {
                if(instance == null)
                {
                    instance = new FileDownLoad();
                    //设置相关的参数
                    httpClientHandler = new HttpClientHandler()
                    {
                        MaxConnectionsPerServer = 10,
                        MaxAutomaticRedirections = 10,
                    };
                    httpClient = new HttpClient(httpClientHandler)
                    {
                        Timeout = TimeSpan.FromSeconds(10),
                    };
                }
                return instance;
            }
        }
        //下载接口,供外部调用
        public void DownLoadInBackGround(string URL, string filename)
        {
            if (!string.IsNullOrEmpty(URL))
            {
                Task.Factory.StartNew(async () => await DownLoadAsync(URL, filename, DownLoadCallBack));
            }
        }

        //Callback也可以设置为DownLoadInBackGround接口的参数,直接使用调用者的Callback
        private void DownLoadCallBack(bool ret, string URL, string fullfilename)
        {
            if (!ret)
            {
                Console.WriteLine("Download result = " + ret);
                Console.WriteLine($"URL = {URL},LocalPath = {fullfilename}");
                return;
            }
        }

        private async Task DownLoadAsync(string URL, string filename, DownLoadMethodInvoker callback)
        {
            Console.WriteLine("URL = " + URL);
            try
            {
                using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, URL))
                {
                    using (HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
                    {
                        long? contentLength = 0;
                        if ((int)response.StatusCode >= 400 && (int)response.StatusCode < 600)
                        {
                            Console.WriteLine("Error statuscode = " + response.StatusCode);
                            return;
                        }
                        try
                        {
                            response.EnsureSuccessStatusCode();
                            contentLength = response.Content.Headers.ContentLength;
                            Console.WriteLine("ContentLength = " + response?.Content?.Headers?.ContentLength);

                            int bufferSize = contentLength > 0 ? (int)contentLength : 1024 * 100;//默认100KB以下
                            byte[] buffer = new byte[bufferSize + 1024 * 2];//添加2KB冗余空间
                            buffer = await response.Content.ReadAsByteArrayAsync();
                            //将读取到的内容写进本地文件
                            using (FileStream fileStream = new FileStream(PATH + filename, FileMode.Create))
                            {
                                Console.WriteLine("Read file complete, filesize = " + bufferSize);
                                fileStream.Write(buffer, 0, bufferSize);
                                Console.WriteLine("Write End, URL = " + URL);
                            }
                            callback?.Invoke(true, URL, PATH + filename);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("exception = " + ex.Message);
                            callback?.Invoke(false, URL, PATH + filename);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception = " + ex.Message);
                callback?.Invoke(false, URL, PATH + filename);
            }
        }
    }
}

2. FileDownLoadTC.cs

编写测试类FileDownLoadTC,提供测试方法,并调用之前实现的下载接口

using System;

namespace CSProject
{
    public class FileDownLoadTC
    {
        private static FileDownLoadTC instance;
        public static FileDownLoadTC Instance
        {
            get
            {
                if(instance == null)
                {
                    instance = new FileDownLoadTC();
                }
                return instance;
            }
        }

        public void Test()
        {
            //图片位置:https://img.infinitynewtab.com/wallpaper/
            for (int i = 1; i <= 300; i++)
            {
                string URL = "https://img.infinitynewtab.com/wallpaper/" + i + ".jpg";
                FileDownLoad.Instance.DownLoadInBackGround(URL, i.ToString("D3") + ".jpg");
            }
        }
    }
}

3. Program.cs

调用测试方法

using System;

namespace CSProject
{
    internal class Program
    {
        static void Main(string[] args)
        {
            FileDownLoadTC.Instance.Test();
            Console.ReadLine();
        }
    }
}
千百度
© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容