123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- using Microsoft.Extensions.Options;
- using OrBit.MesFileServiceNode.Host.Model;
- using System.Security.Cryptography;
- namespace OrBit.MesFileServiceNode.Host.Middleware
- {
- public class UploadFileMiddleware : IMiddleware
- {
- private NodeConfig _nodeConfig;
- private const int BUF_SIZE = 4096;
- public UploadFileMiddleware(IOptions<NodeConfig> config)
- {
- _nodeConfig = config.Value;
- }
- /// <summary>
- /// 获取客户Ip
- /// </summary>
- /// <param name="context"></param>
- /// <returns></returns>
- public string GetClientUserIp(HttpContext context)
- {
- var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
- if (string.IsNullOrEmpty(ip))
- {
- ip = context.Connection.RemoteIpAddress?.ToString();
- }
- return ip;
- }
- public async Task InvokeAsync(HttpContext context, RequestDelegate next)
- {
- //ip限制
- var clientIp = GetClientUserIp(context);
- if (_nodeConfig.AllowIPs != null && _nodeConfig.AllowIPs.Count >0 && !_nodeConfig.AllowIPs.Contains(clientIp))
- {
- context.Response.StatusCode = 200;
- await context.Response.WriteAsync(ExecutionResult.Failed($"IP:{clientIp}不在白名单内").ToJson());
- return;
- }
- var contentType = context.Request.Headers["Content-Type"].ToString();
- //string ConsumerId = context.Request.Headers["ConsumerId"].ToString();
- //var Authorization = context.Request.Headers["Authorization"];
- //var authoResult= await uplodFileService.Authorization(ConsumerId, Authorization);
- //if(authoResult.code== ExecutionState.FAIL)
- //{
- // context.Response.StatusCode = 401;
- // await context.Response.WriteAsJsonAsync(ExecutionResult.Failed("认证失败"));
- // return;
- //}
- //var interfaceConsumer = authoResult.data.ObjCast(new { UploadFolder = "", app = "" });
- var app = context.Request.Headers["app"];
- var UploadFolder = context.Request.Headers["UploadFolder"];
- if (string.IsNullOrEmpty(app))
- {
- context.Response.StatusCode = 200;
- await context.Response.WriteAsJsonAsync(ExecutionResult.Failed("app不能为空"));
- return;
- }
- if (string.IsNullOrEmpty(UploadFolder))
- {
- context.Response.StatusCode = 200;
- await context.Response.WriteAsJsonAsync(ExecutionResult.Failed("UploadFolder不能为空"));
- return;
- }
- List<UploadFileInfo> files = new List<UploadFileInfo>();
- if (contentType.Contains("multipart/form-data"))
- {
- //byte[] buffer = new byte[BUF_SIZE];
- var now = DateTime.Now;
- var year = now.ToString("yyyy");
- var mmdd = now.ToString("MMdd");
- try
- {
- foreach (var s in context.Request.Form.Files)
- {
- var tmpfile = new UploadFileInfo
- {
- ContentType = s.ContentType,
- ExtensionName = Path.GetExtension(s.FileName),
- FileName = s.FileName,
- Length = s.Length
- };
- var folder = Path.Combine(_nodeConfig.PhysicalPath, app, UploadFolder, year, mmdd);
- if (!Directory.Exists(folder))
- {
- Directory.CreateDirectory(folder);
- }
- var tmpFileName = Guid.NewGuid().ToString("n") + tmpfile.ExtensionName;
- var filePath = Path.Combine(folder, tmpFileName);
- // tmpfile.HashID = s.GetHashCode().ToString();
- using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
- {
- s.CopyTo(fileStream);
- fileStream.Flush(true);
- }
- tmpfile.StoragePath = filePath;
- tmpfile.FileUrl = $"{_nodeConfig.Domain}{_nodeConfig.VirtualPath}/{app}/{UploadFolder}/{year}/{mmdd}/{tmpFileName}";
- tmpfile.HashID = s.Name;
- files.Add(tmpfile);
- }
- }
- catch (Exception ex)
- {
- context.Response.StatusCode = 200;
- await context.Response.WriteAsJsonAsync(ExecutionResult.Failed(ex.Message));
- return;
- }
- if (files.Count > 0)
- {
- context.Response.StatusCode = 200;
- await context.Response.WriteAsJsonAsync(ExecutionResult.Success("文件上传成功", files));
- return;
- }
- }
- else
- {
- context.Response.StatusCode = 400;
- await context.Response.WriteAsync(ExecutionResult.Failed("ContentType内容必须是multipart/form-data").ToJson());
- return;
- }
- //var file = await context.Request.StreamFilesModel(async x =>
- //{
- // using (var stream = x.OpenReadStream())
- // while (await stream.ReadAsync(buffer, 0, buffer.Length) > 0) ;
- // files.Add(x);
- //});
- }
- }
- }
|