下载器

DownloadRoutine.cs 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. await DownloadFile();
  77. }
  78. }
  79. public void StopDownload()
  80. {
  81. IsStop = true;
  82. }
  83. public async Task ContinueDownload()
  84. {
  85. if (IsLeisure) return;
  86. IsStop = false;
  87. await DownloadFile();
  88. }
  89. async Task DownloadFile()
  90. {
  91. string dirPath = Path.GetDirectoryName(FileSavePath);
  92. if (!Directory.Exists(dirPath))
  93. Directory.CreateDirectory(dirPath);
  94. using (FileStream fs = new FileStream(FileSavePath, FileMode.OpenOrCreate, FileAccess.Write,FileShare.ReadWrite))
  95. {
  96. _currentDownloadSize = fs.Length;
  97. if (_currentDownloadSize < _totalSzie)
  98. {
  99. fs.Seek(_currentDownloadSize, SeekOrigin.Begin);
  100. UnityWebRequest request = UnityWebRequest.Get(DownLoadUrl);
  101. request.SetRequestHeader("Range", $"bytes={_currentDownloadSize}-");
  102. request.SendWebRequest();
  103. if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
  104. {
  105. onError?.Invoke(request.error);
  106. Debug.Log(request.error); //出现错误 输出错误信息
  107. }
  108. else
  109. {
  110. long index = 0;
  111. while (_currentDownloadSize < _totalSzie)
  112. {
  113. if (IsStop) break;
  114. byte[] data = request.downloadHandler.data;
  115. if (data != null)
  116. {
  117. long length = data.Length - index;
  118. fs.Write(data, (int)index, (int)length);
  119. index += length;
  120. _currentDownloadSize += length;
  121. onProgress?.Invoke((float)Math.Round((double)_currentDownloadSize / _totalSzie,2), _totalSzie, _currentDownloadSize);
  122. if (_currentDownloadSize >= _totalSzie)
  123. {
  124. //下载完成
  125. IsLeisure = true;
  126. onDownloadOver?.Invoke();
  127. break;
  128. }
  129. }
  130. await Task.Yield();
  131. }
  132. }
  133. }
  134. }
  135. }
  136. }
  137. }