UploadFileMiddleware.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. using Microsoft.Extensions.Options;
  2. using OrBit.MesFileServiceNode.Host.Model;
  3. using System.Security.Cryptography;
  4. namespace OrBit.MesFileServiceNode.Host.Middleware
  5. {
  6. public class UploadFileMiddleware : IMiddleware
  7. {
  8. private NodeConfig _nodeConfig;
  9. private const int BUF_SIZE = 4096;
  10. public UploadFileMiddleware(IOptions<NodeConfig> config)
  11. {
  12. _nodeConfig = config.Value;
  13. }
  14. /// <summary>
  15. /// 获取客户Ip
  16. /// </summary>
  17. /// <param name="context"></param>
  18. /// <returns></returns>
  19. public string GetClientUserIp(HttpContext context)
  20. {
  21. var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
  22. if (string.IsNullOrEmpty(ip))
  23. {
  24. ip = context.Connection.RemoteIpAddress?.ToString();
  25. }
  26. return ip;
  27. }
  28. public async Task InvokeAsync(HttpContext context, RequestDelegate next)
  29. {
  30. //ip限制
  31. var clientIp = GetClientUserIp(context);
  32. if (_nodeConfig.AllowIPs != null && _nodeConfig.AllowIPs.Count >0 && !_nodeConfig.AllowIPs.Contains(clientIp))
  33. {
  34. context.Response.StatusCode = 200;
  35. await context.Response.WriteAsync(ExecutionResult.Failed($"IP:{clientIp}不在白名单内").ToJson());
  36. return;
  37. }
  38. var contentType = context.Request.Headers["Content-Type"].ToString();
  39. //string ConsumerId = context.Request.Headers["ConsumerId"].ToString();
  40. //var Authorization = context.Request.Headers["Authorization"];
  41. //var authoResult= await uplodFileService.Authorization(ConsumerId, Authorization);
  42. //if(authoResult.code== ExecutionState.FAIL)
  43. //{
  44. // context.Response.StatusCode = 401;
  45. // await context.Response.WriteAsJsonAsync(ExecutionResult.Failed("认证失败"));
  46. // return;
  47. //}
  48. //var interfaceConsumer = authoResult.data.ObjCast(new { UploadFolder = "", app = "" });
  49. var app = context.Request.Headers["app"];
  50. var UploadFolder = context.Request.Headers["UploadFolder"];
  51. if (string.IsNullOrEmpty(app))
  52. {
  53. context.Response.StatusCode = 200;
  54. await context.Response.WriteAsJsonAsync(ExecutionResult.Failed("app不能为空"));
  55. return;
  56. }
  57. if (string.IsNullOrEmpty(UploadFolder))
  58. {
  59. context.Response.StatusCode = 200;
  60. await context.Response.WriteAsJsonAsync(ExecutionResult.Failed("UploadFolder不能为空"));
  61. return;
  62. }
  63. List<UploadFileInfo> files = new List<UploadFileInfo>();
  64. if (contentType.Contains("multipart/form-data"))
  65. {
  66. //byte[] buffer = new byte[BUF_SIZE];
  67. var now = DateTime.Now;
  68. var year = now.ToString("yyyy");
  69. var mmdd = now.ToString("MMdd");
  70. try
  71. {
  72. foreach (var s in context.Request.Form.Files)
  73. {
  74. var tmpfile = new UploadFileInfo
  75. {
  76. ContentType = s.ContentType,
  77. ExtensionName = Path.GetExtension(s.FileName),
  78. FileName = s.FileName,
  79. Length = s.Length
  80. };
  81. var folder = Path.Combine(_nodeConfig.PhysicalPath, app, UploadFolder, year, mmdd);
  82. if (!Directory.Exists(folder))
  83. {
  84. Directory.CreateDirectory(folder);
  85. }
  86. var tmpFileName = Guid.NewGuid().ToString("n") + tmpfile.ExtensionName;
  87. var filePath = Path.Combine(folder, tmpFileName);
  88. // tmpfile.HashID = s.GetHashCode().ToString();
  89. using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
  90. {
  91. s.CopyTo(fileStream);
  92. fileStream.Flush(true);
  93. }
  94. tmpfile.StoragePath = filePath;
  95. tmpfile.FileUrl = $"{_nodeConfig.Domain}{_nodeConfig.VirtualPath}/{app}/{UploadFolder}/{year}/{mmdd}/{tmpFileName}";
  96. tmpfile.HashID = s.Name;
  97. files.Add(tmpfile);
  98. }
  99. }
  100. catch (Exception ex)
  101. {
  102. context.Response.StatusCode = 200;
  103. await context.Response.WriteAsJsonAsync(ExecutionResult.Failed(ex.Message));
  104. return;
  105. }
  106. if (files.Count > 0)
  107. {
  108. context.Response.StatusCode = 200;
  109. await context.Response.WriteAsJsonAsync(ExecutionResult.Success("文件上传成功", files));
  110. return;
  111. }
  112. }
  113. else
  114. {
  115. context.Response.StatusCode = 400;
  116. await context.Response.WriteAsync(ExecutionResult.Failed("ContentType内容必须是multipart/form-data").ToJson());
  117. return;
  118. }
  119. //var file = await context.Request.StreamFilesModel(async x =>
  120. //{
  121. // using (var stream = x.OpenReadStream())
  122. // while (await stream.ReadAsync(buffer, 0, buffer.Length) > 0) ;
  123. // files.Add(x);
  124. //});
  125. }
  126. }
  127. }