下载器

DownloadRoutine.cs 5.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Threading.Tasks;
  6. using UnityEngine;
  7. using UnityEngine.Networking;
  8. namespace TModule.Runtime
  9. {
  10. public class DownloadRoutine
  11. {
  12. /// <summary>
  13. /// 下载路径
  14. /// </summary>
  15. public string DownLoadUrl { get; set; }
  16. /// <summary>
  17. /// 文件保存路径
  18. /// </summary>
  19. public string FileSavePath { get; set; }
  20. /// <summary>
  21. /// 是否空闲
  22. /// </summary>
  23. public bool IsLeisure { get; set; } = true;
  24. /// <summary>
  25. /// 下载总大小
  26. /// </summary>
  27. private long _totalSzie;
  28. public long TotalSize => _totalSzie;
  29. /// <summary>
  30. /// 已下载大小
  31. /// </summary>
  32. private long _currentDownloadSize;
  33. public long CurrentDownloadSize => _currentDownloadSize;
  34. //停止下载
  35. private bool _isStop;
  36. public bool IsStop
  37. {
  38. get => _isStop ||
  39. #if UNITY_EDITOR
  40. !UnityEditor.EditorApplication.isPlaying
  41. #else
  42. !Application.isPlaying
  43. #endif
  44. ;
  45. set => _isStop = value;
  46. }
  47. public Action onDownloadOver;
  48. /// <summary>
  49. /// 下载中事件 下载进度 总大小 已下载大小
  50. /// </summary>
  51. public Action<float,long,long> onProgress;
  52. public Action<string> onError;
  53. /// <summary>
  54. /// 开始下载
  55. /// </summary>
  56. /// <param name="url"></param>
  57. /// <returns></returns>
  58. public async Task StartDownload(string url,string fileSavePath)
  59. {
  60. DownLoadUrl = url;
  61. FileSavePath = fileSavePath;
  62. IsStop = false;
  63. _currentDownloadSize = 0;
  64. IsLeisure = false;
  65. UnityWebRequest webRequest = UnityWebRequest.Head(DownLoadUrl);
  66. await webRequest.SendWebRequest();
  67. if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
  68. {
  69. onError?.Invoke(webRequest.error);
  70. Debug.Log(webRequest.error); //出现错误 输出错误信息
  71. }
  72. else
  73. {
  74. string info = webRequest.GetResponseHeader("Content-Length");
  75. _totalSzie = long.Parse(info);
  76. Debug.Log($"即将下载{url},下载大小{_totalSzie}");
  77. await DownloadFile();
  78. }
  79. }
  80. public void StopDownload()
  81. {
  82. IsStop = true;
  83. }
  84. public async Task ContinueDownload()
  85. {
  86. if (IsLeisure) return;
  87. IsStop = false;
  88. await DownloadFile();
  89. }
  90. async Task DownloadFile()
  91. {
  92. string dirPath = Path.GetDirectoryName(FileSavePath);
  93. if (!Directory.Exists(dirPath))
  94. Directory.CreateDirectory(dirPath);
  95. using (FileStream fs = new FileStream(FileSavePath, FileMode.OpenOrCreate, FileAccess.Write,FileShare.ReadWrite))
  96. {
  97. _currentDownloadSize = fs.Length;
  98. if (_currentDownloadSize < _totalSzie)
  99. {
  100. fs.Seek(_currentDownloadSize, SeekOrigin.Begin);
  101. UnityWebRequest request = UnityWebRequest.Get(DownLoadUrl);
  102. request.SetRequestHeader("Range", $"bytes={_currentDownloadSize}-");
  103. request.SendWebRequest();
  104. if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
  105. {
  106. onError?.Invoke(request.error);
  107. Debug.Log(request.error); //出现错误 输出错误信息
  108. }
  109. else
  110. {
  111. long index = 0;
  112. while (_currentDownloadSize < _totalSzie)
  113. {
  114. if (IsStop) break;
  115. byte[] data = request.downloadHandler.data;
  116. if (data != null)
  117. {
  118. long length = data.Length - index;
  119. fs.Write(data, (int)index, (int)length);
  120. index += length;
  121. _currentDownloadSize += length;
  122. onProgress?.Invoke((float)Math.Round((double)_currentDownloadSize / _totalSzie,2), _totalSzie, _currentDownloadSize);
  123. if (_currentDownloadSize >= _totalSzie)
  124. {
  125. _currentDownloadSize = 0;
  126. _totalSzie = 0;
  127. DownLoadUrl = string.Empty;
  128. FileSavePath = string.Empty;
  129. onProgress = null;
  130. onError = null;
  131. onDownloadOver?.Invoke();
  132. onDownloadOver = null;
  133. //下载完成
  134. IsLeisure = true;
  135. break;
  136. }
  137. }
  138. await Task.Yield();
  139. }
  140. }
  141. }
  142. }
  143. }
  144. }
  145. }