DownLoadItem.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. public long updateTime;
  45. private UnityWebRequest webRequest;
  46. public void Init(string downLoadPath,string id,ModelType type,long updateTime)
  47. {
  48. this.downLoadPath = downLoadPath;
  49. this.id = id;
  50. this.type = type;
  51. this.updateTime = updateTime;
  52. Debug.Log("UnityWebRequest webRequest"+ downLoadPath);
  53. LoadManager.Instance.downloadQueueList.Enqueue(this);
  54. }
  55. public System.Collections.IEnumerator DownloadFile()
  56. {
  57. string url = HttpAction.Instance.baseurl + HttpAction.file_download;
  58. if (UserInfo.Instance.is20)
  59. {
  60. url = HttpAction.Instance.baseurl20 + HttpAction.file_download;
  61. }
  62. Debug.Log(" 当前下载>>>> " + url + " " + downLoadPath);
  63. using (webRequest = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST))
  64. {
  65. SendMaterials sendImage = new SendMaterials();
  66. sendImage.url = downLoadPath;
  67. string jsonString = JsonConvert.SerializeObject(sendImage);
  68. Debug.Log("body :" + jsonString);
  69. Debug.Log("Token :" + UserInfo.Instance.Token);
  70. byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  71. webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  72. //DownloadHandlerTexture texture = new DownloadHandlerTexture(true);
  73. //webRequest.downloadHandler = texture;
  74. webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  75. //switch (type)
  76. //{
  77. // case ModelType.Image:
  78. // webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerTexture(true);
  79. // break;
  80. // case ModelType.Video:
  81. // webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerAudioClip("", AudioType.ACC);
  82. // break;
  83. // case ModelType.ABModel:
  84. // webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerFile(Application.persistentDataPath + downLoadPath);
  85. // break;
  86. // case ModelType.Text:
  87. // default:
  88. // webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  89. // break;
  90. //}
  91. webRequest.SetRequestHeader("authorization", UserInfo.Instance.Token);
  92. webRequest.SetRequestHeader("Content-Type", "application/json");
  93. yield return webRequest.SendWebRequest();
  94. while (!webRequest.isDone)
  95. {
  96. // 此处可以显示下载进度条等UI操作
  97. progress = webRequest.downloadProgress;
  98. onProgress?.Invoke(progress);
  99. // Debug.Log("Download Progress: " + progress);
  100. yield return new WaitForFixedUpdate();
  101. }
  102. if (webRequest.isHttpError || webRequest.isNetworkError)
  103. {
  104. Debug.LogError("Download Failed: " + webRequest.error);
  105. // 下载失败
  106. downLoadState = webRequest.error;
  107. isDownLoad = false;
  108. }
  109. else
  110. {
  111. Debug.Log(webRequest.isDone + " " + webRequest.downloadHandler.data.Length);
  112. // Debug.LogError("Download Failed: " + webRequest.error);
  113. downLoadData = webRequest.downloadHandler.data;
  114. isDownLoad = true;
  115. downLoadState = "下载成功";
  116. }
  117. //if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
  118. //{
  119. // //Debug.LogError("Download Failed: " + webRequest.error);
  120. // downLoadData = webRequest.downloadHandler.data;
  121. // isDownLoad = true;
  122. //}
  123. //else
  124. //{
  125. // //switch (type)
  126. // //{
  127. // // case ModelType.Image:
  128. // // break;
  129. // // case ModelType.Video:
  130. // // break;
  131. // // case ModelType.ABModel:
  132. // // var ab = DownloadHandlerAssetBundle.GetContent(webRequest);
  133. // // downLoadObject = ab;
  134. // // AssetBundleRequest abRequest = ab.LoadAssetAsync(ab.GetAllAssetNames()[0]);
  135. // // yield return abRequest;
  136. // // GameObject obj = abRequest.asset as GameObject;
  137. // // Debug.Log(" AssetBundleRequest>>>> " + obj.name);
  138. // // break;
  139. // // case ModelType.Text:
  140. // // break;
  141. // // default:
  142. // // break;
  143. // //}
  144. // // 下载失败
  145. //}
  146. callback?.Invoke(isDownLoad);
  147. }
  148. //string url = HttpAction.baseurl + HttpAction.file_download;
  149. //SendMaterials sendImage = new SendMaterials();
  150. //sendImage.url = downLoadPath;
  151. //if (UserInfo.Instance.is20)
  152. //{
  153. // url = HttpAction.baseurl20 + HttpAction.file_download;
  154. //}
  155. //string jsonString = JsonMapper.ToJson(sendImage);
  156. //if (UserInfo.Instance.is20)
  157. // Debug.Log(string.Format("url:{0} postData:{1}", url, jsonString));
  158. //using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
  159. //{
  160. // byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  161. // webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  162. // DownloadHandlerTexture texture = new DownloadHandlerTexture(true);
  163. // webRequest.downloadHandler = texture;
  164. // // Debug.Log(value.mObj.localSavePath);
  165. // // webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerFile(value.mObj.localSavePath);
  166. // // Debug.Log(value.mObj.localSavePath);
  167. // webRequest.SetRequestHeader("authorization", UserInfo.Instance.Token);
  168. // webRequest.SetRequestHeader("Content-Type", "application/json");
  169. // yield return webRequest.SendWebRequest();
  170. // if (webRequest.isHttpError || webRequest.isNetworkError)
  171. // {
  172. // Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
  173. // }
  174. // else
  175. // {
  176. // if (callback != null)
  177. // {
  178. // try
  179. // {
  180. // }
  181. // catch (Exception e)
  182. // {
  183. // }
  184. // try
  185. // {
  186. // Texture2D texture2 = texture.texture;
  187. // Sprite createSprite = Sprite.Create(texture2, new Rect(0, 0, texture2.width, texture2.height), Vector2.zero);
  188. // Debug.Log(webRequest.downloadHandler.data.Length + " " + texture2.width);
  189. // Texture2D texture3 = texture.texture;
  190. // }
  191. // catch (Exception e)
  192. // {
  193. // // ErrorLogPanel.Instance.Show(" 图片生成出现错误 " + jsonString);
  194. // }
  195. // ////转为字节数组
  196. // // File.WriteAllBytes(value.mObj.localSavePath, webRequest.downloadHandler.data);
  197. // }
  198. // }
  199. //}
  200. }
  201. public DownLoadMaterial data;
  202. public void DownloadFileMsg()
  203. {
  204. Debug.Log("查询需要下载的updateTime"+updateTime + downLoadPath);
  205. MsgHandler.AddListener(downLoadPath, HandleMsg);
  206. data = new DownLoadMaterial();
  207. data.downLoadPath = downLoadPath;
  208. data.localLoadPath = Application.persistentDataPath + "/Material/" + Path.GetFileName(downLoadPath);
  209. if(type == ModelType.vuforial)
  210. data.localLoadPath = Application.persistentDataPath + "/StreamingAssets/Vuforia/GHZVuforia." + downLoadPath.Split('.')[1];
  211. data.type = ((int)type).ToString();
  212. Debug.LogError("DownloadFileMsg");
  213. DownloadResManager.Instance.DownLoad(data);
  214. }
  215. private void HandleMsg(Msg msg)
  216. {
  217. if (msg.Value != null)
  218. {
  219. downLoadData = (byte[])msg.Value;
  220. isDownLoad = true;
  221. downLoadState = "下载成功";
  222. callback?.Invoke(isDownLoad);
  223. MsgHandler.RemoveListener(Application.persistentDataPath + "" + downLoadPath, HandleMsg);
  224. }
  225. else
  226. {
  227. // isDownLoad = true;
  228. downLoadState = "下载失败";
  229. StartCoroutine(ReDownloadFileMsg());
  230. }
  231. }
  232. IEnumerator ReDownloadFileMsg()
  233. {
  234. yield return null;
  235. DownloadFileMsg();
  236. }
  237. Dictionary<string, string> requestHeader = new Dictionary<string, string>(); // header
  238. public void initHead()
  239. {
  240. requestHeader.Clear();
  241. if (UserInfo.Instance.Token != "" && UserInfo.Instance.Token != null)
  242. {
  243. // requestHeader.Add("x-token", UserInfo.Instance.Token);
  244. Debug.Log("ADD Token");
  245. requestHeader.Add("authorization", UserInfo.Instance.Token);
  246. }
  247. requestHeader.Add("Content-Type", "application/json");
  248. }
  249. private void OnDestroy()
  250. {
  251. // 断开下载连接
  252. if (webRequest != null && !webRequest.isDone)
  253. {
  254. webRequest.Abort();
  255. }
  256. }
  257. }