Explorar o código

add ftp upload and downlaod
exclude ftp upload download from middleware

Robert hai 1 ano
pai
achega
7b6eb42aaf

+ 66 - 7
EVCB_OCPP.WEBAPI/Controllers/FileController.cs

@@ -9,17 +9,36 @@ using Microsoft.AspNetCore.Mvc;
 using EVCB_OCPP.WEBAPI;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.StaticFiles;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Configuration;
 
 namespace EVCB_OCPP.WEBAPI.Controllers
 {
     [ApiExplorerSettings(IgnoreApi = true)]
+    [Route("file")]
     public class FileController : ControllerBase
     {
-        private readonly IWebHostEnvironment webHostEnvironment;
+        private readonly FileExtensionContentTypeProvider typeProvider;
+        //private readonly IWebHostEnvironment webHostEnvironment;
+        private readonly ILogger<FileController> logger;
+        private readonly string ftpPath;
 
-        public FileController(IWebHostEnvironment webHostEnvironment)
+        public FileController(
+            FileExtensionContentTypeProvider typeProvider,
+            //IWebHostEnvironment webHostEnvironment,
+            IConfiguration configuration,
+            ILogger<FileController> logger)
         {
-            this.webHostEnvironment = webHostEnvironment;
+            this.typeProvider = typeProvider;
+            //this.webHostEnvironment = webHostEnvironment;
+            this.logger = logger;
+
+            this.ftpPath = "/home/UploadFiles/Diagnostics";
+            if (!string.IsNullOrEmpty(configuration["FtpPath"]))
+            {
+                this.ftpPath = configuration["FtpPath"];
+            }
         }
 
         [HttpPut]
@@ -29,7 +48,13 @@ namespace EVCB_OCPP.WEBAPI.Controllers
 
             var ctx = HttpContext;// HttpContextHelper.Current;
             //var root = ctx.Server.MapPath("~/UploadFiles/Diagnostics");
-            string root = string.Format($"{webHostEnvironment.ContentRootPath}/UploadFiles/Diagnostics");
+            //string root = string.Format("{webHostEnvironment.ContentRootPath}/UploadFiles/Diagnostics");
+
+            if (!Directory.Exists(ftpPath))
+            {
+                Directory.CreateDirectory(ftpPath);
+            }
+
             //var provider = new MultipartFileStreamProvider(root);
 
             try
@@ -43,7 +68,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers
 
                 //await Request.Content.ReadAsMultipartAsync(provider);
 
-                foreach (var file in Request.Form.Files)
+                foreach (IFormFile file in Request.Form.Files)
                 {
                     if (file.Headers.ContentType.Contains("application/zip"))
                     {
@@ -51,13 +76,14 @@ namespace EVCB_OCPP.WEBAPI.Controllers
                         name = name.Trim('"');
 
                         //var localFileName = file.LocalFileName;
-                        var filePath = Path.Combine(root, name);
+                        var filePath = Path.Combine(ftpPath, name);
                         if (!System.IO.File.Exists(filePath))
                         {
                             //System.IO.File.Move(localFileName, filePath);
+                            using (var istream = file.OpenReadStream())
                             using (var fstream = System.IO.File.Open(filePath, FileMode.CreateNew))
                             {
-                                await file.CopyToAsync(fstream);
+                                await istream.CopyToAsync(fstream);
                             }
                         }
                         else
@@ -103,11 +129,44 @@ namespace EVCB_OCPP.WEBAPI.Controllers
             }
             catch (Exception ex)
             {
+                logger.LogError(ex.Message);
+                logger.LogError(ex.StackTrace);
                 //return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.ToString());
                 return StatusCode(StatusCodes.Status500InternalServerError, ex.ToString());
             }
 
 
         }
+
+        [HttpGet("{FileName}")]
+        public IActionResult GetFile([FromRoute] string FileName)
+        {
+            try
+            {
+
+                //string root = string.Format($"{webHostEnvironment.ContentRootPath}/UploadFiles/Diagnostics");
+                var filePath = Path.Combine(ftpPath, FileName);
+
+                if (!FileName.ToLower().EndsWith(".zip") ||
+                    !System.IO.File.Exists(filePath))
+                {
+                    return StatusCode(StatusCodes.Status400BadRequest);
+                }
+
+                var stream = System.IO.File.OpenRead(filePath);
+                if (!typeProvider.TryGetContentType(FileName, out var contentType))
+                {
+                    return StatusCode(StatusCodes.Status500InternalServerError);
+                }
+                //return new FileStreamResult(stream, "application/zip");
+                return File(stream, contentType, fileDownloadName: FileName, enableRangeProcessing: false);
+            }
+            catch (Exception e)
+            {
+                logger.LogError(e.Message);
+                logger.LogError(e.StackTrace);
+                return null;
+            }
+        }
     }
 }

+ 11 - 5
EVCB_OCPP.WEBAPI/Startup.cs

@@ -81,11 +81,17 @@ namespace EVCB_OCPP.WEBAPI
                 app.UseExceptionHandler("/Home/Error");
             }
 
-            app.UseMiddleware<PerformaceMonitorMiddleware>(new PerformaceMonitorMiddlewareOptions() { Label = "Outter" });
-            app.EnableRequestBodyRewind();
-            app.UseMiddleware<ExceptionMiddleware>();
-            app.UseMiddleware<APILogMiddleware>();
-            app.UseMiddleware<PerformaceMonitorMiddleware>(new PerformaceMonitorMiddlewareOptions() { Label = "Inter" });
+            app.UseWhen(
+                context => !context.Request.Path.StartsWithSegments("/file"),
+                appBuilder =>
+                {
+                    appBuilder.UseMiddleware<PerformaceMonitorMiddleware>(new PerformaceMonitorMiddlewareOptions() { Label = "Outter" });
+                    appBuilder.EnableRequestBodyRewind();
+                    appBuilder.UseMiddleware<ExceptionMiddleware>();
+                    appBuilder.UseMiddleware<APILogMiddleware>();
+                    appBuilder.UseMiddleware<PerformaceMonitorMiddleware>(new PerformaceMonitorMiddlewareOptions() { Label = "Inter" });
+                }
+                );
 
             //app.UseStaticFiles();
             app.UseRouting();

+ 1 - 0
EVCB_OCPP.WEBAPI/appsettings.json

@@ -12,6 +12,7 @@
   "ClientValidationEnabled": true,
   "UnobtrusiveJavaScriptEnabled": true,
   "StatisticsAPI": "http://ocpp.phihong.com.tw/StatisticsReportApi/",
+  "FtpPath": "/home/UploadFiles/Diagnostics",
   "ConnectionStrings": {
     "Main20DBContext": "data source=zerova-ev-dev.database.windows.net;initial catalog=Docker_Main;;persist security info=True;user id=azdevsoftware;password=1h52dev#az;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
     "MeterValue20DBContext": "data source=zerova-ev-dev.database.windows.net;initial catalog=Docker_Main;;persist security info=True;user id=azdevsoftware;password=1h52dev#az;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",