DownLoadItem.cs 9.6 KB

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