UpLoadFileRequest.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. /* ==============================================================================
  2. * 功能描述:UpLoadFileRequest
  3. * 创 建 者:Garrett
  4. * 创建日期:2018/3/23 15:19:52
  5. * ==============================================================================*/
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Text;
  13. using System.Windows;
  14. using SAGA.MBI.Common;
  15. using Utilities;
  16. using Aliyun.OSS;
  17. using Aliyun.OSS.Common;
  18. using Newtonsoft.Json.Linq;
  19. using SAGA.DotNetUtils;
  20. using SAGA.DotNetUtils.Encrypt;
  21. using SAGA.DotNetUtils.Extend;
  22. using SAGA.DotNetUtils.FileOperate;
  23. using SAGA.DotNetUtils.Http;
  24. using SAGA.DotNetUtils.Logger;
  25. using SAGA.DotNetUtils.Others;
  26. using SAGA.MBI.DataArrange;
  27. using SAGA.MBI.FileStream;
  28. using SAGA.MBI.JsonConvert;
  29. using SAGA.MBI.Login;
  30. using SAGA.MBI.Tools;
  31. using SAGA.RevitUtils;
  32. namespace SAGA.MBI.RequestData
  33. {
  34. /// <summary>
  35. /// UpLoadFileRequest
  36. /// </summary>
  37. public class UpLoadFileRequest
  38. {
  39. /// <summary>
  40. /// 是否使用oss
  41. /// </summary>
  42. /// <returns></returns>
  43. public static bool UseOss()
  44. {
  45. var flag = ConfigurationUtil.Default.GetSettingValue("UpDownFlag");
  46. return flag==null||flag.Trim() == "0";
  47. }
  48. #region Download
  49. /// <summary>
  50. /// 下载指定文件到指定
  51. /// </summary>
  52. /// <param name="downPath"></param>
  53. /// <param name="fileName"></param>
  54. /// <returns></returns>
  55. public static bool DownLoadRevitFile(string downPath, string fileName)
  56. {
  57. try
  58. {
  59. if (!Directory.Exists(downPath))
  60. Directory.CreateDirectory(downPath);
  61. var filePath = Path.Combine(downPath, fileName);
  62. //如果文件存在,删除重新下载
  63. File.Delete(filePath);
  64. //文件下载
  65. var url =
  66. $"{MBIConst.ImageServiceLocalHost}image-service/common/file_get/{fileName}?systemId={MBIConst.RevitServiceId}";
  67. WebClient wc = new WebClient();
  68. wc.Headers.Add("postman-token", "8efb60cb-a34c-592e-6e61-5412b1dfc1bb");
  69. wc.Headers.Add("cache-control", "no-cache");
  70. wc.DownloadFile(new Uri(url), filePath);
  71. wc.Dispose();
  72. }
  73. catch (Exception e)
  74. {
  75. Console.WriteLine(e);
  76. return false;
  77. }
  78. finally
  79. {
  80. }
  81. return true;
  82. }
  83. #endregion
  84. #region DownLoadAsync
  85. private static WinMFMDownloadProcress windown = null;
  86. public static WinMFMDownloadProcress GetProcessWin()
  87. {
  88. return windown;
  89. }
  90. /// <summary>
  91. /// 显示下载窗体
  92. /// </summary>
  93. public static void ShowDownloadWindow(string floorName, string fullPath, int count, int cur)
  94. {
  95. if (windown == null)
  96. {
  97. windown = new WinMFMDownloadProcress();
  98. windown.Show();
  99. }
  100. windown.LabelFloorName = $"正在下载{floorName}层模型文件,请稍后。。。";
  101. windown.LabelPath = fullPath;
  102. windown.Count = count;
  103. windown.Cur = cur;
  104. }
  105. /// <summary>
  106. /// 下载指定文件到指定
  107. /// </summary>
  108. /// <param name="downPath"></param>
  109. /// <param name="fileName"></param>
  110. /// <returns></returns>
  111. public static bool DownLoadFileAsync(Tuple<string, int, string> tuple, int count, int cur)
  112. {
  113. if (!UpLoadFileRequest.UseOss())
  114. {
  115. return FileContentTransferUnit.DownLoadFileAsync(tuple, count, cur);
  116. }
  117. bool result = true;
  118. string fullPath = tuple.Item1;
  119. string floorName = tuple.Item3;
  120. string cloudName = CommonTool.GetCloudRevitName(fullPath);
  121. int state = tuple.Item2;
  122. if (state == 2)
  123. FloorFileOperate.BakFile(fullPath);
  124. string key = $"{MBIConst.OssClientFileKey}{cloudName}";
  125. DownLoadNew:
  126. OssClient client;
  127. if (WebRequestProxy.IsOnline(out ClientConfiguration conf))
  128. {
  129. client = new OssClient(MBIConst.Endpoint, MBIConst.AccessKeyId, MBIConst.AccessKeySecret, conf);
  130. }
  131. else
  132. {
  133. client = new OssClient(MBIConst.Endpoint, MBIConst.AccessKeyId, MBIConst.AccessKeySecret);
  134. }
  135. int timeoutNum = 20;
  136. long totalLength = 0;
  137. try
  138. {
  139. string bucketName = MBIConst.BucketName;
  140. ShowDownloadWindow(tuple.Item3, fullPath, count, cur);
  141. var getObjectRequest = new GetObjectRequest(bucketName, key);
  142. //getObjectRequest.StreamTransferProgress += DownStreamProgressCallback;
  143. var buffer = new byte[1024 * 1024];
  144. long stargIndex = 0;
  145. getObjectRequest.StreamTransferProgress += (s, args) =>
  146. {
  147. var tempTrans = stargIndex + args.TransferredBytes;
  148. var tempTotal = stargIndex + args.TotalBytes;
  149. var currentData = Math.Round(((double)tempTrans)/ tempTotal *100d, 3);
  150. Debug.WriteLine("ProgressCallback - TotalBytes:{0}M, TransferredBytes:{1}M,上传百分比:{2}%",
  151. Math.Round(tempTotal / 1024d / 1024,3), Math.Round(tempTrans / 1024d / 1024,3), currentData);
  152. windown?.Update(currentData);
  153. //currentData >= 100d
  154. if (tempTrans >= tempTotal && windown!=null&&windown.Count == windown.Cur)
  155. {
  156. //MessageBox.Show("数据上传完毕!");
  157. CloseDownloadWin(true, false);
  158. }
  159. };
  160. using (var fs = new MemoryStream())
  161. {
  162. ReDownload:
  163. getObjectRequest.SetRange(stargIndex, -1);
  164. OssObject ossObject = client.GetObject(getObjectRequest);
  165. //设置下载超时时间
  166. ossObject.ResponseStream.ReadTimeout = 60 * 1000;//*20;
  167. if (totalLength == 0)
  168. {
  169. totalLength = ossObject.ContentLength;
  170. }
  171. using (var stream = ossObject.Content)
  172. {
  173. var bytesRead = 0;
  174. try
  175. {
  176. while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
  177. {
  178. fs.Write(buffer, 0, bytesRead);
  179. }
  180. }
  181. catch (WebException e)
  182. {
  183. #region 超时重试
  184. if (0 < timeoutNum-- && e.Message.Contains("超时"))
  185. {
  186. stargIndex = fs.Length;
  187. //timeoutNum--;
  188. goto ReDownload;
  189. }
  190. throw;
  191. #endregion
  192. }
  193. if (fs.Length < totalLength)
  194. {
  195. stargIndex = fs.Length;
  196. goto ReDownload;
  197. }
  198. }
  199. FileStreamOperate.WriteFile(fs.ToArray(), fullPath);
  200. #region 下载后Md5较验
  201. string md5 = MD5Tools.GetMD5HashFromFileByBase64(fullPath);
  202. //下载后的文件md5校验
  203. if (client.GetObjectMetadata(bucketName, key).ContentMd5 != md5)
  204. {
  205. string per = Math.Round((fs.Length / (double)totalLength) * 100, 3) + "%";
  206. string errorMessage = ($"楼层 {floorName} MD5校验失败,本地与服务器不一致!下载进度{per}");
  207. if (fs.Length== totalLength)
  208. {
  209. if (MessageShowBase.Question(errorMessage + "\r\n是否重新下载该层文件"))
  210. {
  211. goto DownLoadNew;
  212. }
  213. }
  214. else
  215. {
  216. MessageShowBase.Infomation(errorMessage);
  217. }
  218. MailLog.Log("下载MD5异常", errorMessage);
  219. result = false;
  220. }
  221. #endregion
  222. }
  223. Log4Net.Debug($"Get object:{key} succeeded");
  224. }
  225. catch (Exception ex)
  226. {
  227. MessageShowBase.Infomation("Revit文件下载失败!\r\n"+ex.Message+"\r\n"+ex.StackTrace);
  228. result = false;
  229. CloseDownloadWin(result,false);
  230. }
  231. return result;
  232. }
  233. /// <summary>
  234. /// 下载进度条
  235. /// </summary>
  236. /// <param name="sender"></param>
  237. /// <param name="args"></param>
  238. private static void DownStreamProgressCallback(object sender, StreamTransferProgressArgs args)
  239. {
  240. try
  241. {
  242. var currentData = Math.Round(args.TransferredBytes * 100d / args.TotalBytes, 3);
  243. Debug.WriteLine("ProgressCallback - TotalBytes:{0}M, TransferredBytes:{1}M,上传百分比:{2}%",
  244. args.TotalBytes / 1024 / 1024, args.TransferredBytes / 1024 / 1024, currentData);
  245. windown?.Update(currentData);
  246. if (currentData >= 100d && windown.Count == windown.Cur)
  247. {
  248. //MessageBox.Show("数据上传完毕!");
  249. CloseDownloadWin(true, false);
  250. }
  251. }
  252. catch (Exception ex)
  253. {
  254. throw;
  255. }
  256. }
  257. /// <summary>
  258. /// 关闭下载窗口
  259. /// </summary>
  260. public static void CloseDownloadWin(bool issucess, bool hasTip = true)
  261. {
  262. if (windown != null)
  263. {
  264. windown?.Close();
  265. windown = null;
  266. }
  267. if (hasTip)
  268. MessageShowBase.Infomation(issucess ? "Revit模型文件下载成功!" : "Revit模型文件下载失败!");
  269. }
  270. #endregion
  271. #region Upload
  272. /// <summary>
  273. /// 将本地文件上传到指定的服务器(HttpWebRequest方法)
  274. /// </summary>
  275. /// <returns></returns>
  276. public static string UpLoadFile(string downPath, string fileName, string url)
  277. {
  278. var responseValue = string.Empty;
  279. var filePath = downPath;
  280. if (!File.Exists(downPath))
  281. filePath = Path.Combine(downPath, fileName);
  282. try
  283. {
  284. var request = (HttpWebRequest)WebRequest.Create(url);
  285. request.Timeout = 60000;
  286. request.Method = "POST";
  287. //每次上传4k
  288. int bufferLength = 40960;
  289. byte[] buffer = new byte[bufferLength];
  290. // 要上传的文件
  291. System.IO.FileStream fs = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read);
  292. BinaryReader r = new BinaryReader(fs);
  293. int size = r.Read(buffer, 0, bufferLength);
  294. //request.ContentLength = bufferLength;
  295. Stream postStream = null;
  296. try
  297. {
  298. while (size > 0)
  299. {
  300. postStream = request.GetRequestStream();
  301. postStream.Write(buffer, 0, bufferLength);
  302. size = r.Read(buffer, 0, bufferLength);
  303. }
  304. }
  305. catch (Exception e)
  306. {
  307. Console.WriteLine(e);
  308. throw;
  309. }
  310. finally
  311. {
  312. fs.Close();
  313. postStream?.Close();
  314. r.Close();
  315. }
  316. //返回数据
  317. using (var response = (HttpWebResponse)request.GetResponse())
  318. {
  319. if (response.StatusCode != HttpStatusCode.OK)
  320. {
  321. var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
  322. throw new ApplicationException(message);
  323. }
  324. // grab the response
  325. using (var responseStream = response.GetResponseStream())
  326. {
  327. if (responseStream != null)
  328. using (var reader = new StreamReader(responseStream))
  329. {
  330. responseValue = reader.ReadToEnd();
  331. }
  332. }
  333. }
  334. }
  335. catch (Exception e)
  336. {
  337. MessageShowBase.Show(e);
  338. }
  339. return responseValue;
  340. }
  341. /// <summary>
  342. /// 上传到文件服务器的Revit目录中
  343. /// </summary>
  344. /// <returns></returns>
  345. public static string UpLoadRevitFile(string downPath, string fileName)
  346. {
  347. string systemId = MBIConst.RevitServiceId;
  348. string secret = MBIConst.RevitServiceSecret;
  349. //文件下载
  350. string url =
  351. $"{MBIConst.ImageServiceLocalHost}image-service/common/file_upload?systemId={systemId}&secret={secret}&key={fileName}&overwrite=true";
  352. return UpLoadFile(downPath, fileName, url);
  353. }
  354. /// <summary>
  355. /// 上传到文件服务器的Dev目录中
  356. /// </summary>
  357. /// <returns></returns>
  358. public static string UpLoadDevFile(string downPath, string fileName)
  359. {
  360. string systemId = MBIConst.DevServiceId;
  361. string secret = MBIConst.DevServiceSecret;
  362. //文件下载
  363. string url =
  364. $"{MBIConst.ImageServiceLocalHost}image-service/common/file_upload?systemId={systemId}&secret={secret}&key={fileName}&overwrite=true";
  365. return UpLoadFile(downPath, fileName, url);
  366. }
  367. /// <summary>
  368. /// 上传到图片服务器的Dev目录中
  369. /// </summary>
  370. /// <returns></returns>
  371. public static string UpLoadDevImage(string downPath, string fileName)
  372. {
  373. string systemId = MBIConst.DevServiceId;
  374. string secret = MBIConst.DevServiceSecret;
  375. //文件下载
  376. string url =
  377. $"{MBIConst.ImageServiceLocalHost}image-service/common/image_upload?systemId={systemId}&secret={secret}&key={fileName}&overwrite=true";
  378. return UpLoadFile(downPath, fileName, url);
  379. }
  380. #endregion
  381. #region UploadAsync
  382. private static WinMFMUploadProcress win = null;
  383. public static WinMFMUploadProcress GetUpProcessWin()
  384. {
  385. return win;
  386. }
  387. /// <summary>
  388. /// 显示上传窗体
  389. /// </summary>
  390. /// <param name="filePath"></param>
  391. public static void ShowUploadWindow(string floorName, string filePath, int count, int cur)
  392. {
  393. if (win == null)
  394. {
  395. win = new WinMFMUploadProcress();
  396. win.Show();
  397. }
  398. win.FloorName = $"正在上传{floorName}层模型文件,请稍后。。。";
  399. win.LabelPath = filePath;
  400. win.Count = count;
  401. win.Cur = cur;
  402. }
  403. /// <summary>
  404. /// 关闭上传窗体
  405. /// </summary>
  406. public static void CloseUploadWindow(bool issucess, bool hasTip = false)
  407. {
  408. if (win != null)
  409. {
  410. win?.Close();
  411. win = null;
  412. }
  413. if (hasTip)
  414. MessageBox.Show(issucess ? "Revit模型文件上传成功!" : "Revit文件上传失败!");
  415. }
  416. /// <summary>
  417. /// 上传Revit文件到服务器
  418. /// </summary>
  419. /// <param name="filePath"></param>
  420. /// <param name="fileName"></param>
  421. /// <returns></returns>
  422. public static bool UpLoadRevitAsync(string floorName, string filePath, string fileName, int count, int cur)
  423. {
  424. if (!UpLoadFileRequest.UseOss())
  425. {
  426. return FileContentTransferUnit.UpLoadRevitAsync(floorName, filePath, fileName,count,cur);
  427. }
  428. bool result = true;
  429. string key = $"{MBIConst.OssClientFileKey}{fileName}";
  430. OssClient client = new OssClient(MBIConst.Endpoint, MBIConst.AccessKeyId, MBIConst.AccessKeySecret);
  431. try
  432. {
  433. using (var fs = new MemoryStream(FileStreamOperate.ReadFile(filePath)))
  434. {
  435. string bucketName = MBIConst.BucketName;
  436. var putObjectRequest = new PutObjectRequest(bucketName, key, fs);
  437. ShowUploadWindow(floorName, filePath, count, cur);
  438. putObjectRequest.StreamTransferProgress += StreamProgressCallback;
  439. client.PutObject(putObjectRequest);
  440. #region 上传后MD5较验
  441. string md5 = MD5Tools.GetMD5HashFromFileByBase64(filePath);
  442. //上传后的文件md5校验
  443. if (client.GetObjectMetadata(bucketName, key).ContentMd5 != md5)
  444. {
  445. string errorMessage = ($"楼层 {floorName} MD5校验失败,本地与服务器不一致!");
  446. MailLog.Log("上传MD5异常", errorMessage);
  447. MessageShowBase.Infomation(errorMessage);
  448. //不关闭窗体
  449. // throw new Exception(errorMessage);
  450. }
  451. #endregion
  452. }
  453. Console.WriteLine("Put object:{0} succeeded", key);
  454. }
  455. catch (Exception ex)
  456. {
  457. MessageShowBase.Infomation("Revit文件上传载失败!\r\n" + ex.Message + "\r\n" + ex.StackTrace);
  458. result = false;
  459. CloseUploadWindow(result,false);
  460. }
  461. return result;
  462. }
  463. /// <summary>
  464. /// 上传进度条
  465. /// </summary>
  466. /// <param name="sender"></param>
  467. /// <param name="args"></param>
  468. private static void StreamProgressCallback(object sender, StreamTransferProgressArgs args)
  469. {
  470. var currentData = Math.Round(args.TransferredBytes * 100d / args.TotalBytes, 3);
  471. Debug.WriteLine("ProgressCallback - TotalBytes:{0}M, TransferredBytes:{1}M,上传百分比:{2}%",
  472. args.TotalBytes / 1024 / 1024, args.TransferredBytes / 1024 / 1024, currentData);
  473. win?.Update(currentData);
  474. if (currentData >= 100d)
  475. {
  476. CloseUploadWindow(true, false);
  477. }
  478. }
  479. #endregion
  480. #region Del
  481. /// <summary>
  482. /// 删除服务器文件
  483. /// </summary>
  484. /// <returns></returns>
  485. public static string DeleteFile(string url, string key)
  486. {
  487. //文件下载
  488. try
  489. {
  490. JObject jObject = new JObject();
  491. JArray keyArray = new JArray();
  492. keyArray.Add(key);
  493. jObject.Add("keys", keyArray);
  494. string postData = jObject.ToString();
  495. RestClient client = new RestClient(url, HttpVerb.POST, postData);
  496. string request = client.PostRequest();
  497. return request;
  498. }
  499. catch (Exception e)
  500. {
  501. MessageShowBase.Show(e);
  502. }
  503. return null;
  504. }
  505. /// <summary>
  506. /// 删除文件服务器Revit目录下的数据
  507. /// </summary>
  508. /// <param name="key"></param>
  509. /// <returns></returns>
  510. public static string DeleteRevitFile(string key)
  511. {
  512. string systemId = MBIConst.RevitServiceId;
  513. string secret = MBIConst.RevitServiceSecret;
  514. string url =
  515. $"{MBIConst.ImageServiceLocalHost}image-service/common/files_delete?systemId={systemId}&secret={secret}";
  516. return DeleteFile(url, key);
  517. }
  518. /// <summary>
  519. /// 删除文件服务器Dev目录下的数据
  520. /// </summary>
  521. /// <param name="key"></param>
  522. /// <returns></returns>
  523. public static string DeleteDevFile(string key)
  524. {
  525. string systemId = MBIConst.DevServiceId;
  526. string secret = MBIConst.DevServiceSecret;
  527. string url =
  528. $"{MBIConst.ImageServiceLocalHost}image-service/common/files_delete?systemId={systemId}&secret={secret}";
  529. return DeleteFile(url, key);
  530. }
  531. /// <summary>
  532. /// 删除图片服务器Dev目录的图片
  533. /// </summary>
  534. /// <param name="key"></param>
  535. /// <returns></returns>
  536. public static string DeleteDevImage(string key)
  537. {
  538. string systemId = MBIConst.DevServiceId;
  539. string secret = MBIConst.DevServiceSecret;
  540. string url =
  541. $"{MBIConst.ImageServiceLocalHost}image-service/common/images_delete?systemId={systemId}&secret={secret}";
  542. return DeleteFile(url, key);
  543. }
  544. #endregion
  545. #region 一级底层封装
  546. /*
  547. * 1、上传接口:URL,(传路径|传bytes) 系统及Id
  548. * 2、下载接口:URL,(传路径|返回bytes)
  549. * 3、返回文件列表:前缀,数量默认
  550. * 4、删除文件:(列表|单独文件)
  551. */
  552. public static bool UploadFile(FileServiceSetting setting, string key, Byte[] bytes)
  553. {
  554. try
  555. {
  556. string url =
  557. $"{MBIConst.ImageServiceLocalHost}image-service/common/file_upload?systemId={setting.SystemId}&secret={setting.Secret}&key={key}&overwrite=true";
  558. MemoryStream stream = new MemoryStream(bytes);
  559. var result = RequestClient.UploadFile(url, stream);
  560. JObject rj = JObject.Parse(result);
  561. if (rj["Result"].ToString() == "success")
  562. {
  563. return true;
  564. }
  565. //结果暂时不处理
  566. throw new Exception(rj["ResultMsg"].ToString());
  567. return false;
  568. }
  569. catch (Exception e)
  570. {
  571. throw;
  572. }
  573. }
  574. public static bool UploadFile(FileServiceSetting setting, string key, string filePath)
  575. {
  576. try
  577. {
  578. var bytes = File.ReadAllBytes(filePath);
  579. var result = UploadFile(setting, key, bytes);
  580. //结果暂时不处理
  581. return true;
  582. }
  583. catch (Exception)
  584. {
  585. throw;
  586. }
  587. }
  588. public static byte[] DownloadFile(FileServiceSetting setting, string key)
  589. {
  590. var url =
  591. $"{MBIConst.ImageServiceLocalHost}image-service/common/file_get/{key}?systemId={setting.SystemId}";
  592. try
  593. {
  594. return RequestClient.DownloadFile(url);
  595. }
  596. catch (Exception e)
  597. {
  598. throw;
  599. }
  600. return null;
  601. }
  602. public static bool DownloadFile(FileServiceSetting setting, string key, string filePath)
  603. {
  604. try
  605. {
  606. string parentPath = Directory.GetParent(filePath).FullName;
  607. if (!Directory.Exists(parentPath))
  608. Directory.CreateDirectory(parentPath);
  609. //if (!File.Exists(filePath))
  610. // File.Create(filePath);
  611. var reuslt = DownloadFile(setting, key);
  612. if (reuslt == null)
  613. throw new Exception("下载文件失败");
  614. File.WriteAllBytes(filePath, reuslt);
  615. return true;
  616. }
  617. catch (Exception)
  618. {
  619. throw;
  620. }
  621. }
  622. /// <summary>
  623. /// 根据指定前缀获取文件列表
  624. /// </summary>
  625. /// <param name="prefix"></param>
  626. /// <returns></returns>
  627. public static List<string> GetFiles(FileServiceSetting setting, string prefix)
  628. {
  629. List<string> files = new List<string>();
  630. string url = $"{MBIConst.ImageServiceLocalHost}image-service/common/files_list?systemId={setting.SystemId}&secret={setting.Secret}";
  631. JObject jObject = new JObject();
  632. jObject.Add("prefix", prefix);
  633. var result = RequestClient.Post(url, jObject);
  634. JObject resultJson = JObject.Parse(result);
  635. files = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(resultJson["Content"].ToString()) ?? new List<string>();
  636. return files;
  637. }
  638. /// <summary>
  639. /// 删除传入文件信息
  640. /// </summary>
  641. /// <param name="setting"></param>
  642. /// <param name="inputFiles"></param>
  643. /// <returns>成功删除的文件</returns>
  644. public static List<string> DeleteFiles(FileServiceSetting setting, List<string> inputFiles)
  645. {
  646. List<string> delFiles = new List<string>();
  647. if (inputFiles.IsNullOrEmptyExt())
  648. return delFiles;
  649. string url = $"{MBIConst.ImageServiceLocalHost}image-service/common/files_delete?systemId={setting.SystemId}&secret={setting.Secret}";
  650. JObject jObject = new JObject();
  651. JArray array = new JArray();
  652. inputFiles.ForEach(s => array.Add(s));
  653. jObject.Add("keys", array);
  654. var result = RequestClient.Post(url, jObject);
  655. JObject resultJson = JObject.Parse(result);
  656. delFiles = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(resultJson["Content"].ToString()) ?? new List<string>();
  657. return delFiles;
  658. }
  659. public static bool DeleteFile(FileServiceSetting setting, string file)
  660. {
  661. var delFile = DeleteFiles(setting, new List<string>() { file })?.FirstOrDefault();
  662. return delFile == file;
  663. }
  664. #endregion
  665. }
  666. /// <summary>
  667. /// 文件服务设置
  668. /// </summary>
  669. public class FileServiceSetting
  670. {
  671. static FileServiceSetting()
  672. {
  673. RevitSetting = new FileServiceSetting() { SystemId = MBIConst.RevitServiceId, Secret = MBIConst.RevitServiceSecret };
  674. DevSetting = new FileServiceSetting() { SystemId = MBIConst.DevServiceId, Secret = MBIConst.DevServiceSecret };
  675. }
  676. /// <summary>
  677. /// 系统ID
  678. /// </summary>
  679. public string SystemId { get; set; } = "";
  680. /// <summary>
  681. /// 系统密码
  682. /// </summary>
  683. public string Secret { get; set; } = "";
  684. public static FileServiceSetting RevitSetting { get; private set; }
  685. public static FileServiceSetting DevSetting { get; private set; }
  686. }
  687. }