DownLoadItem.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. using LitJson;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Text;
  8. using UnityEngine;
  9. using UnityEngine.Networking;
  10. public class DownLoadItem : MonoBehaviour
  11. {
  12. public delegate void DownLoadCallBack(bool b);
  13. public delegate void DownLoadPressOn(float f);
  14. //下载回调
  15. public DownLoadCallBack callback;
  16. //下载进度回调
  17. public DownLoadPressOn onProgress;
  18. //下载ID
  19. public string id;
  20. /// <summary>
  21. /// 下载地址
  22. /// </summary>
  23. public string downLoadPath;
  24. /// <summary>
  25. /// 是否下载成功
  26. /// </summary>
  27. public bool isDownLoad;
  28. /// <summary>
  29. /// 下载成功后的文件
  30. /// </summary>
  31. public byte[] downLoadData;
  32. public object downLoadObject;
  33. public ModelType type;
  34. /// <summary>
  35. /// 进度条
  36. /// </summary>
  37. public float progress;
  38. /// <summary>
  39. /// 下载后状态
  40. /// </summary>
  41. public string downLoadState;
  42. //下载后是否有处理
  43. public bool isAction;
  44. private UnityWebRequest webRequest;
  45. public void Init(string downLoadPath,string id,ModelType type)
  46. {
  47. this.downLoadPath = downLoadPath;
  48. this.id = id;
  49. this.type = type;
  50. LoadManager.Instance.downloadQueueList.Enqueue(this);
  51. }
  52. public System.Collections.IEnumerator DownloadFile()
  53. {
  54. string url = HttpAction.baseurl + HttpAction.file_download;
  55. if (UserInfo.Instance.is20)
  56. {
  57. url = HttpAction.baseurl20 + HttpAction.file_download;
  58. }
  59. Debug.Log(" 当前下载>>>> " + url + " " + downLoadPath);
  60. using (webRequest = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST))
  61. {
  62. SendMaterials sendImage = new SendMaterials();
  63. sendImage.url = downLoadPath;
  64. string jsonString = JsonConvert.SerializeObject(sendImage);
  65. Debug.Log("body :" + jsonString);
  66. Debug.Log("Token :" + UserInfo.Instance.Token);
  67. byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  68. webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  69. //DownloadHandlerTexture texture = new DownloadHandlerTexture(true);
  70. //webRequest.downloadHandler = texture;
  71. webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  72. //switch (type)
  73. //{
  74. // case ModelType.Image:
  75. // webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerTexture(true);
  76. // break;
  77. // case ModelType.Video:
  78. // webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerAudioClip("", AudioType.ACC);
  79. // break;
  80. // case ModelType.ABModel:
  81. // webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerFile(Application.persistentDataPath + downLoadPath);
  82. // break;
  83. // case ModelType.Text:
  84. // default:
  85. // webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  86. // break;
  87. //}
  88. webRequest.SetRequestHeader("authorization", UserInfo.Instance.Token);
  89. webRequest.SetRequestHeader("Content-Type", "application/json");
  90. yield return webRequest.SendWebRequest();
  91. while (!webRequest.isDone)
  92. {
  93. // 此处可以显示下载进度条等UI操作
  94. progress = webRequest.downloadProgress;
  95. onProgress?.Invoke(progress);
  96. // Debug.Log("Download Progress: " + progress);
  97. yield return new WaitForFixedUpdate();
  98. }
  99. if (webRequest.isHttpError || webRequest.isNetworkError)
  100. {
  101. Debug.LogError("Download Failed: " + webRequest.error);
  102. // 下载失败
  103. downLoadState = webRequest.error;
  104. isDownLoad = false;
  105. }
  106. else
  107. {
  108. Debug.Log(webRequest.isDone + " " + webRequest.downloadHandler.data.Length);
  109. // Debug.LogError("Download Failed: " + webRequest.error);
  110. downLoadData = webRequest.downloadHandler.data;
  111. isDownLoad = true;
  112. downLoadState = "下载成功";
  113. }
  114. //if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
  115. //{
  116. // //Debug.LogError("Download Failed: " + webRequest.error);
  117. // downLoadData = webRequest.downloadHandler.data;
  118. // isDownLoad = true;
  119. //}
  120. //else
  121. //{
  122. // //switch (type)
  123. // //{
  124. // // case ModelType.Image:
  125. // // break;
  126. // // case ModelType.Video:
  127. // // break;
  128. // // case ModelType.ABModel:
  129. // // var ab = DownloadHandlerAssetBundle.GetContent(webRequest);
  130. // // downLoadObject = ab;
  131. // // AssetBundleRequest abRequest = ab.LoadAssetAsync(ab.GetAllAssetNames()[0]);
  132. // // yield return abRequest;
  133. // // GameObject obj = abRequest.asset as GameObject;
  134. // // Debug.Log(" AssetBundleRequest>>>> " + obj.name);
  135. // // break;
  136. // // case ModelType.Text:
  137. // // break;
  138. // // default:
  139. // // break;
  140. // //}
  141. // // 下载失败
  142. //}
  143. callback?.Invoke(isDownLoad);
  144. }
  145. //string url = HttpAction.baseurl + HttpAction.file_download;
  146. //SendMaterials sendImage = new SendMaterials();
  147. //sendImage.url = downLoadPath;
  148. //if (UserInfo.Instance.is20)
  149. //{
  150. // url = HttpAction.baseurl20 + HttpAction.file_download;
  151. //}
  152. //string jsonString = JsonMapper.ToJson(sendImage);
  153. //if (UserInfo.Instance.is20)
  154. // Debug.Log(string.Format("url:{0} postData:{1}", url, jsonString));
  155. //using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
  156. //{
  157. // byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  158. // webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  159. // DownloadHandlerTexture texture = new DownloadHandlerTexture(true);
  160. // webRequest.downloadHandler = texture;
  161. // // Debug.Log(value.mObj.localSavePath);
  162. // // webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerFile(value.mObj.localSavePath);
  163. // // Debug.Log(value.mObj.localSavePath);
  164. // webRequest.SetRequestHeader("authorization", UserInfo.Instance.Token);
  165. // webRequest.SetRequestHeader("Content-Type", "application/json");
  166. // yield return webRequest.SendWebRequest();
  167. // if (webRequest.isHttpError || webRequest.isNetworkError)
  168. // {
  169. // Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
  170. // }
  171. // else
  172. // {
  173. // if (callback != null)
  174. // {
  175. // try
  176. // {
  177. // }
  178. // catch (Exception e)
  179. // {
  180. // }
  181. // try
  182. // {
  183. // Texture2D texture2 = texture.texture;
  184. // Sprite createSprite = Sprite.Create(texture2, new Rect(0, 0, texture2.width, texture2.height), Vector2.zero);
  185. // Debug.Log(webRequest.downloadHandler.data.Length + " " + texture2.width);
  186. // Texture2D texture3 = texture.texture;
  187. // }
  188. // catch (Exception e)
  189. // {
  190. // // ErrorLogPanel.Instance.Show(" 图片生成出现错误 " + jsonString);
  191. // }
  192. // ////转为字节数组
  193. // // File.WriteAllBytes(value.mObj.localSavePath, webRequest.downloadHandler.data);
  194. // }
  195. // }
  196. //}
  197. }
  198. public void DownloadFileMsg()
  199. {
  200. MsgHandler.AddListener(Application.persistentDataPath + "" + downLoadPath, HandleMsg);
  201. DownLoadMaterial data = new DownLoadMaterial();
  202. data.downLoadPath = downLoadPath;
  203. data.localLoadPath = Application.persistentDataPath + "/Material/" + Path.GetFileName(downLoadPath);
  204. data.updataTime = 0;
  205. data.type = type.ToString();
  206. DownloadResManager.Instance.DownLoad(data);
  207. }
  208. private void HandleMsg(Msg msg)
  209. {
  210. if (msg.Value != null)
  211. {
  212. downLoadData = (byte[])msg.Value;
  213. isDownLoad = true;
  214. downLoadState = "下载成功";
  215. }
  216. else
  217. {
  218. isDownLoad = true;
  219. downLoadState = "下载失败";
  220. }
  221. callback?.Invoke(isDownLoad);
  222. MsgHandler.RemoveListener(Application.persistentDataPath + "" + downLoadPath, HandleMsg);
  223. }
  224. Dictionary<string, string> requestHeader = new Dictionary<string, string>(); // header
  225. public void initHead()
  226. {
  227. requestHeader.Clear();
  228. if (UserInfo.Instance.Token != "" && UserInfo.Instance.Token != null)
  229. {
  230. // requestHeader.Add("x-token", UserInfo.Instance.Token);
  231. Debug.Log("ADD Token");
  232. requestHeader.Add("authorization", UserInfo.Instance.Token);
  233. }
  234. requestHeader.Add("Content-Type", "application/json");
  235. }
  236. private void OnDestroy()
  237. {
  238. // 断开下载连接
  239. if (webRequest != null && !webRequest.isDone)
  240. {
  241. webRequest.Abort();
  242. }
  243. }
  244. }