1 UnityWebRequest下载

unity自带的下载方式,优点很明显:封装很好,使用简便,与unity使用兼容性很好且跨平台问题少;对应的缺点:扩展性差.

1.1 存在内存中供程序使用或者下载一些小文件

例子:

   public IEnumerator DownloadFile(string url, string contentName){string downloadFileName = "";
#if UNITY_EDITORdownloadFileName = Path.Combine(Application.dataPath, contentName);
#elif UNITY_ANDROIDdownloadFileName = Path.Combine(Application.persistentDataPath, contentName);
#endifusing (UnityWebRequest webRequest = UnityWebRequest.Get(url)){yield return webRequest.SendWebRequest();if (webRequest.isNetworkError){Debug.LogError(webRequest.error);}else{DownloadHandler fileHandler = webRequest.downloadHandler;using (MemoryStream memory = new MemoryStream(fileHandler.data)){byte[] buffer = new byte[1024 * 1024];FileStream file = File.Open(downloadFileName, FileMode.OpenOrCreate);int readBytes;while ((readBytes = memory.Read(buffer, 0, buffer.Length)) > 0){file.Write(buffer, 0, readBytes);}file.Close();}}}}

1.2 新版unity新增了DownloadHandlerFile的支持函数,可以直接将文件下载到外存

例子:

 public IEnumerator DownloadVideoFile01(Uri uri, string downloadFileName, Slider sliderProgress ){using (UnityWebRequest downloader = UnityWebRequest.Get(uri)){downloader.downloadHandler = new DownloadHandlerFile(downloadFileName);print("开始下载");downloader.SendWebRequest();print("同步进度条");while (!downloader.isDone){//print(downloader.downloadProgress);sliderProgress.value = downloader.downloadProgress;sliderProgress.GetComponentInChildren<Text>().text = (downloader.downloadProgress* 100).ToString("F2") + "%";yield return null;}if (downloader.error != null){Debug.LogError(downloader.error);}else{print("下载结束");sliderProgress.value = 1f;sliderProgress.GetComponentInChildren<Text>().text = 100.ToString("F2") + "%";}}}

2 C# http下载

.net的http下载很灵活,不同的下载方式,如流式下载,分块下载,还是断点续传等等,可扩展性非常强;但是因为是.net框架,有时发布到其他平台会有莫名其妙的bug;

送上封装好的代码,转载的代码,找不到出处,希望原作见谅:PS:很好用

   /// <summary>/// 下载器/// </summary>public class Downloader{/// <summary>/// 取消下载的错误描述/// </summary>const string CANCELLED_ERROR = "Cancelled";/// <summary>/// 重写的WebClient类/// </summary>class DownloadWebClient : WebClient{readonly int _timeout;public DownloadWebClient(int timeout = 60){if (null == ServicePointManager.ServerCertificateValidationCallback){ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);}_timeout = timeout * 1000;}protected override WebRequest GetWebRequest(Uri address){HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;//request.ProtocolVersion = HttpVersion.Version10;request.Timeout = _timeout;request.ReadWriteTimeout = _timeout;request.Proxy = null;return request;}protected override WebResponse GetWebResponse(WebRequest request){return base.GetWebResponse(request);}private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors){//总是接受,通过Https验证return true;}}DownloadWebClient _client;bool _isDone;/// <summary>/// 是否操作完成/// </summary>public bool isDone{get{return _isDone;}}float _progress;/// <summary>/// 操作进度/// </summary>public float progress{get{return _progress;}}string _error;/// <summary>/// 错误信息/// </summary>public string error{get{return _error;}}long _totalSize;/// <summary>/// 文件总大小/// </summary>public long totalSize{get{return _totalSize;}}long _loadedSize;/// <summary>/// 已完成大小/// </summary>public long loadedSize{get{return _loadedSize;}}/// <summary>/// 是否已销毁/// </summary>public bool isDisposeed{get { return _client == null ? true : false; }}readonly string _savePath;/// <summary>/// 文件的保存路径/// </summary>public string savePath{get { return _savePath; }}readonly bool _isAutoDeleteWrongFile;/// <summary>/// /// </summary>/// <param name="url">下载的文件地址</param>/// <param name="savePath">文件保存的地址</param>/// <param name="isAutoDeleteWrongFile">是否自动删除未下完的文件</param>public Downloader(string url, string savePath, bool isAutoDeleteWrongFile = true){_isAutoDeleteWrongFile = isAutoDeleteWrongFile;_savePath = savePath;_client = new DownloadWebClient();_client.DownloadProgressChanged += OnDownloadProgressChanged;_client.DownloadFileCompleted += OnDownloadFileCompleted;Uri uri = new Uri(url);_client.DownloadFileAsync(uri, savePath);}/// <summary>/// 销毁对象,会停止所有的下载/// </summary>public void Dispose(){if (null != _client){_client.CancelAsync();}}void ClearClient(){_client.DownloadProgressChanged -= OnDownloadProgressChanged;_client.DownloadFileCompleted -= OnDownloadFileCompleted;_client.Dispose();_client = null;}/// <summary>/// 下载文件完成/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs e){ClearClient();_isDone = true;if (e.Cancelled || e.Error != null){_error = e.Error == null ? CANCELLED_ERROR : e.Error.Message;if (_isAutoDeleteWrongFile){try{//删除没有下载完成的文件File.Delete(_savePath);}catch{}}}}/// <summary>/// 下载进度改变/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e){_loadedSize = e.BytesReceived;_totalSize = e.TotalBytesToReceive;if (0 == _totalSize){_progress = 0;}else{_progress = _loadedSize / (float)_totalSize;}}}

Unity下载文件的方式小结相关推荐

  1. python爬虫下载-python爬虫之下载文件的方式总结以及程序实例

    python爬虫之下载文件的方式以及下载实例 目录 第一种方法:urlretrieve方法下载 第二种方法:request download 第三种方法:视频文件.大型文件下载 实战演示 第一种方法: ...

  2. python 下载文件-python爬虫之下载文件的方式总结以及程序实例

    python爬虫之下载文件的方式以及下载实例 目录 第一种方法:urlretrieve方法下载 第二种方法:request download 第三种方法:视频文件.大型文件下载 实战演示 第一种方法: ...

  3. Python下载文件的方式

    python下载文件的三种方式: 同时设置下载后文件名字和保存路径,默认文件路径是在执行的py文件同目录下 1. import urllib.requesturl = 'http://xxx.xxx. ...

  4. unity 下载文件 断点续传

    基类 首先先创建一个基类,里面存放下载需要的一些数据,例如文件url,下载存放路径等等. public abstract class DownloadItem {/// <summary> ...

  5. 原生jq下载文件的方式

    way-1 后端返回链接----直接通过链接下载 $.ajax({url:'...',.........success:function (result){window.location = resu ...

  6. 前端:下载文件实现方式及跨域下载(详解)

    前言:本文详细介绍在开发过程中前端如何与后端配合实现文件下载至本地,并详细说明特殊格式文件如何处理.如果你是一名前端开发者,恰好需要实现后端文件下载至本地的需求,那么恭喜你本篇文章一定会帮到你! 需求 ...

  7. 微信公众号开发不能下载文件处理方式

    在微信公众号网页开发,下载流文件,无效果.这里处理方式是直接打开连接在微信中预览~~~~ 使用 window.open() 打开连接预览(android是打开浏览器,ios是预览)~~~ 特此记录

  8. unity下载文件三(http异步下载)

    异步下载,顾名思义就是不影响你主线程使用客户端的时候,人家在后台搞你的明堂. 直接入主题,既然要下载,首先得请求,请求成功之后进行回调,这就是一个异步过程,异步回调的时间不可控. 1.首先请求下载. ...

  9. delphi日期格式显示及文件打开方式小结

    今天要显示delphi日期格式为"xxxx年xx月xx日"形式,原本以为格式化串就是这样写的,后来发现不行,搜索后才知是按格式"dddddd". 参考:在Del ...

最新文章

  1. 我在不炎熱也不抑鬱的秋天,依然不抽煙
  2. Joseph cicyle's algorithm
  3. android倒计时录制视频下载,android录制视屏(预览,倒计时)
  4. sphinx4 FrontEnd流程分析
  5. 一文读懂YOLOv5 与 YOLOv4
  6. 微服务 java9模块化_Java9系列第8篇-Module模块化编程
  7. 终于过了。。。。。。。。。。。
  8. java.lang.ClassNotFoundException: org.apache.htrace.SamplerBuilder
  9. pytorch3d在linux下安装
  10. html——inline、block与block-inline区别
  11. hdu 1217 Arbitrage (最小生成树)
  12. WinForm 单例模式实例
  13. AIDL解析(一):AIDL原理解析
  14. 网络防火墙开发二三事 转
  15. K8S 三种探针 readinessProbe、livenessProbe和startupProbe
  16. 年度案例大数据盘点之Spark篇
  17. QQ语音通话通过蓝牙发送语音给耳机的一些问题(Android O)
  18. 英语口语练习四十三之7种方式说“温柔”
  19. UVA_12676_Inverting Huffman(哈夫曼树)
  20. mysql fastdfs_FastDFS监控系统Fastdfs-zyc配置

热门文章

  1. 微信收货地址开发分享
  2. 第五届新疆省ACM-ICPC程序设计竞赛(重现赛)
  3. HyperMesh 实用教程(一)组件
  4. linux startx无效_startx启动失败的几个解决方法
  5. android 锁屏音乐控制
  6. 小红书标签怎么添加?小红书标签对作品有什么影响
  7. 网络安全与攻防-常见网络安全攻防
  8. 点击不同按钮,eachart图显示不同数据,动态的控制echarts折线的条数
  9. Allegro172版本DFM规则之DFT outline
  10. 技术人生:故事之八 OFFICE是软件打字机?