You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 lines
3.4 KiB

2 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Web;
  6. namespace EasyBL.Handler
  7. {
  8. /// <summary>
  9. /// FileManager 的摘要说明
  10. /// </summary>
  11. public class ListFileManager : Handler
  12. {
  13. private enum ResultState
  14. {
  15. Success,
  16. InvalidParam,
  17. AuthorizError,
  18. IOError,
  19. PathNotFound
  20. }
  21. private int Start;
  22. private int Size;
  23. private int Total;
  24. private ResultState State;
  25. private String PathToList;
  26. private String[] FileList;
  27. private String[] SearchExtensions;
  28. public ListFileManager(HttpContext context, string pathToList, string[] searchExtensions)
  29. : base(context)
  30. {
  31. this.SearchExtensions = searchExtensions.Select(x => x.ToLower()).ToArray();
  32. this.PathToList = pathToList;
  33. }
  34. public override void Process()
  35. {
  36. try
  37. {
  38. Start = String.IsNullOrEmpty(Request["start"]) ? 0 : Convert.ToInt32(Request["start"]);
  39. Size = String.IsNullOrEmpty(Request["size"]) ? Config.GetInt("imageManagerListSize") : Convert.ToInt32(Request["size"]);
  40. }
  41. catch (FormatException)
  42. {
  43. State = ResultState.InvalidParam;
  44. WriteResult();
  45. return;
  46. }
  47. var buildingList = new List<String>();
  48. try
  49. {
  50. var localPath = Server.MapPath(PathToList);
  51. buildingList.AddRange(Directory.GetFiles(localPath, "*", SearchOption.AllDirectories)
  52. .Where(x => SearchExtensions.Contains(Path.GetExtension(x).ToLower()))
  53. .Select(x => PathToList + x.Substring(localPath.Length).Replace("\\", "/")));
  54. Total = buildingList.Count;
  55. FileList = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();
  56. }
  57. catch (UnauthorizedAccessException)
  58. {
  59. State = ResultState.AuthorizError;
  60. }
  61. catch (DirectoryNotFoundException)
  62. {
  63. State = ResultState.PathNotFound;
  64. }
  65. catch (IOException)
  66. {
  67. State = ResultState.IOError;
  68. }
  69. finally
  70. {
  71. WriteResult();
  72. }
  73. }
  74. private void WriteResult()
  75. {
  76. WriteJson(new
  77. {
  78. state = GetStateString(),
  79. list = FileList?.Select(x => new { url = x }),
  80. start = Start,
  81. size = Size,
  82. total = Total
  83. });
  84. }
  85. private string GetStateString()
  86. {
  87. switch (State)
  88. {
  89. case ResultState.Success:
  90. return "SUCCESS";
  91. case ResultState.InvalidParam:
  92. return "参数不正确";
  93. case ResultState.PathNotFound:
  94. return "路径不存在";
  95. case ResultState.AuthorizError:
  96. return "文件系统权限不足";
  97. case ResultState.IOError:
  98. return "文件系统读取错误";
  99. default:
  100. return "未知错误";
  101. }
  102. }
  103. }
  104. }