Browse Source

feat:1、广告按站名划分文件夹存储;2、广告最大大小通过站点表配置

Zhenghanjv 2 months ago
parent
commit
75f8770656

+ 7 - 7
Platform/AI.Platform.Page/Pages/Media/Media.razor.cs

@@ -197,12 +197,12 @@ public partial class Media
 
         var query =  _Repository.AsQueryable()
             .LeftJoin<SiteEntity>((media,site) => media.BusinessUnitId == site.Id)
-            .WhereIF(filterData.searchFileName != null, it => it.FileName.Contains(filterData.searchFileName))
-            .WhereIF(filterData.searchMediaUploader != null, it => it.Uploader.Contains(filterData.searchMediaUploader))
-            .WhereIF(filterData.searchMediaState != null && filterData.searchMediaState != -1, it => it.MediaState == filterData.searchMediaState)
-            .WhereIF(filterData.searchStartTime != null && filterData.searchEndTime != null, it => it.StartTime >= filterData.searchStartTime && it.EndTime <= filterData.searchEndTime)
-            .WhereIF(filterData.searchEffecitiveTime != null && filterData.searchFailureTime != null, it => it.EffectiveTime >= filterData.searchEffecitiveTime && it.FailureTime <= filterData.searchFailureTime)
-            .WhereIF(filterData.searchStartEditTime != null && filterData.searchEndEditTime != null, it => it.EditTime >= filterData.searchStartEditTime && it.EditTime <= filterData.searchEndEditTime);
+            .WhereIF(filterData.searchFileName != null, media => media.FileName.Contains(filterData.searchFileName))
+            .WhereIF(filterData.searchMediaUploader != null, media => media.Uploader.Contains(filterData.searchMediaUploader))
+            .WhereIF(filterData.searchMediaState != null && filterData.searchMediaState != -1, media => media.MediaState == filterData.searchMediaState)
+            .WhereIF(filterData.searchStartTime != null && filterData.searchEndTime != null, media => media.StartTime >= filterData.searchStartTime && media.EndTime <= filterData.searchEndTime)
+            .WhereIF(filterData.searchEffecitiveTime != null && filterData.searchFailureTime != null, media => media.EffectiveTime >= filterData.searchEffecitiveTime && media.FailureTime <= filterData.searchFailureTime)
+            .WhereIF(filterData.searchStartEditTime != null && filterData.searchEndEditTime != null, media => media.EditTime >= filterData.searchStartEditTime && media.EditTime <= filterData.searchEndEditTime);
 
         if (filterData.searchMachineStateList.IsNotNullOrEmpty())
         {
@@ -259,7 +259,7 @@ public partial class Media
     /// </summary>
     private void HandleReset()
     {
-
+        filterData = new();
     }
 
     /// <summary>

+ 160 - 15
Platform/AI.Platform.Page/Pages/Media/UpdateMediaDialog.razor

@@ -1,6 +1,7 @@
 @using AI.Platform.Page.Pages.Media.Model
 @using System.Threading.Tasks
 @using System.Text.Json
+@using System.Net.Http.Headers
 
 @if (IsVisible && Model != null)
 {
@@ -86,7 +87,7 @@
                         <div class="filter_colume">
                             <div class="filter_row_around">
                                 <span>下发油站</span>
-                                <SimpleSelect DefaultValue="@Model.BusinessUnitID.ToString()" OnSelectedItemChanged="@(data => OnSelectItemChange(2, data, editContext))" style="width:80%">
+                                <SimpleSelect DefaultValue="@Model.BusinessUnitID.ToString()" Disabled="@(Model.Type == 2)" OnSelectedItemChanged="@(data => OnSelectItemChange(2, data, editContext))" style="width:80%">
                                     <SelectOptions>
                                         @foreach (var department in Model.siteInfos)
                                         {
@@ -108,20 +109,25 @@
                     </div>
 
                     @if (Model?.Type == 1)
-                    {
-                        <Upload class="filter_row" Name="file" style="justify-content:center" Action="@Global.MediaUploadUrl"
-                                Headers="uploadFileHeader"
-                                @bind-FileList="fileList" ListType="UploadListType.PictureCard"
-                                ShowUploadList="true" ShowDownloadIcon="true" ShowPreviewIcon="true" ShowRemoveIcon="true" ShowButton="fileList.Count < 1"
-                                OnCompleted="OnUploadCompleted" OnRemove="OnRemove">
-                            <div>
-                                <Icon Type="plus" />
-                                <div className="ant-upload-text">上传文件</div>
+                    {   
+                        <div class="upload_box">
+                            <div class="upload-container">
+                                <div class="custom-upload-content">
+                                    <Icon Type="upload" />
+                                    <div>点击上传文件</div>
+                                    @if (selectedFile != null)
+                                    {
+                                        <div class="file-name">@selectedFile.Name</div>
+                                    }
+                                </div>
+
+                                <InputFile OnChange="OnFileSelected"
+                                           Class="transparent-input-file" />
                             </div>
-                        </Upload>
+                        </div>
                     }
 
-                    <div class="filter_row" style="justify-content:end;margin-top:5%;">
+                    <div class="filter_row" style="justify-content:end;margin-top:1%;">
                         <button Icon="plus" type="button" @onclick="() => HandleSubmit(editContext)" style="margin-right:2%">确定</button>
                         <button Icon="reload" @onclick="Close" style="margin-right:2%">取消</button>
                     </div>
@@ -129,7 +135,13 @@
                 
             }
 
-            
+            @if (isUploading)
+            {
+                <div style="position: absolute; inset: 0; background: rgba(255,255,255,0.6); z-index: 100;">
+                    <Spin Tip="上传中..."
+                          Style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);" />
+                </div>
+            }
 
             @if(Model?.Type == 3)
             {
@@ -196,9 +208,16 @@
 
     private Dictionary<string, string> uploadFileHeader = new Dictionary<string, string>();
 
+    [Inject] public HttpClient Http { get; set; } = default!;
+    [Inject] public MessageService Message { get; set; } = default!;
+    private ElementReference inputFileRef;
+    private IBrowserFile? selectedFile;
+    private bool isUploading = false;
+
     protected override void OnParametersSet()
     {
         fileList.Clear();
+        selectedFile = null;
         uploadFileHeader["Authorization"] = Global.GetToken();
         EffecitiveTime = new DateTime?[]
         {
@@ -242,6 +261,70 @@
         }
     }
 
+    private void OnFileSelected(InputFileChangeEventArgs e)
+    {
+        // if (e.Value is not IBrowserFile file) return;
+        var siteinfo = Model.siteInfos.Find(it => it.Id == Model.BusinessUnitID);
+        if (siteinfo != null && e.File.Size > siteinfo.MaxSize)
+        {
+            Message.Error("上传文件超过限制大小");
+            return;
+        }
+
+        selectedFile = e.File;
+        Model.FileName = e.File.Name;
+    }
+
+    private async Task UploadFile()
+    {
+        if (isUploading || selectedFile == null) return;
+
+        isUploading = true;
+        StateHasChanged();
+
+        try
+        {
+            const long maxFileSize = 300 * 1024 * 1024; // 300 MB
+
+            using var stream = selectedFile.OpenReadStream(maxFileSize);
+            using var content = new MultipartFormDataContent();
+
+            content.Add(new StreamContent(stream), "file", selectedFile.Name);
+            content.Add(new StringContent(Model.BusinessUnitID.ToString()), "siteId");
+
+            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5076/api/File/UploadMedia")
+            {
+                Content = content
+            };
+            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Global.Token);
+
+            // 发送请求
+            var httpResponse = await Http.SendAsync(request);
+            httpResponse.EnsureSuccessStatusCode();
+
+            var responseJson = await httpResponse.Content.ReadAsStringAsync();
+            var response = JsonSerializer.Deserialize<Service.Output.Response<Service.Output.MediaFileUploadOutput>>(responseJson);
+
+            Model.FileName = response?.data.fileName ?? "";
+            Model.SavePath = response?.data.savePath ?? "";
+            Model.GuidFileName = response?.data.guidName ?? "";
+            Model.FileExtension = response?.data.extension ?? "";
+
+
+            // Message.Success("上传成功!");
+            // selectedFile = null; // 清空
+        }
+        catch (Exception ex)
+        {
+            Message.Error( $"上传失败: {ex.Message}");
+            Model.FileName = "";
+        }
+        finally
+        {
+            isUploading = false;
+            StateHasChanged();
+        }
+    }
 
     /// <summary>
     /// 上传文件完毕
@@ -249,6 +332,7 @@
     /// <param name="info"></param>
     private void OnUploadCompleted(UploadInfo info)
     {
+        // _upload.StartUpload()
         string responseJson =  info.File.Response;
         var response = JsonSerializer.Deserialize<Service.Output.Response<Service.Output.MediaFileUploadOutput>>(responseJson);
 
@@ -259,6 +343,11 @@
 
     }
 
+    /// <summary>
+    /// 文件上传组件——删除事件
+    /// </summary>
+    /// <param name="fileItem"></param>
+    /// <returns></returns>
     private async Task<bool> OnRemove(UploadFileItem fileItem)
     {
         Console.WriteLine(fileItem);
@@ -286,6 +375,12 @@
                 var siteinfo = Model.siteInfos.Find(it => it.Id.ToString().Equals(value));
                 if (siteinfo != null)
                 {
+                    if(selectedFile != null && selectedFile.Size > siteinfo.MaxSize)
+                    {
+                        Message.Error("上传文件超过限制大小");
+                        selectedFile = null;
+                        Model.FileName = "";
+                    }
                     Model.GroupID = siteinfo.ParentId;
                     Model.BusinessUnitID = siteinfo.Id;
 
@@ -311,7 +406,7 @@
         {
             Model.MachineStateList = values.ToList();
         }
-        
+
         editContext.NotifyFieldChanged(FieldIdentifier.Create(() => Model.MachineStateList));
     }
 
@@ -349,10 +444,18 @@
 
     private async Task HandleSubmit(EditContext editContext)
     {
-        
+
         if(editContext.Validate())
         {
+            if(Model.BusinessUnitID <= 0)
+            {
+                Message.Error("请绑定油站");
+                return;
+            }
+
+            await UploadFile();
             await onSure();
+            
         }
     }
 
@@ -437,4 +540,46 @@
         width: 100%;
         margin-top: 2%;
     }
+
+    .upload_box{
+        display:flex;
+        flex-direction:column;
+        justify-content:center;
+        align-items:center;
+        margin-top:1%;
+    }
+
+    .upload-container {
+        position: relative;
+        display: inline-block;
+        width: 50%;
+        height:160px;
+        padding:3%;
+    }
+
+    .custom-upload-content {
+        width: 100%;
+        height: 100%;
+        border: 2px dashed #d9d9d9;
+        border-radius: 8px;
+        display: flex;
+        flex-direction: column;
+        align-items: center;
+        justify-content: center;
+        cursor: pointer;
+        background-color: #fafafa;
+        z-index: 1;
+        position: relative;
+    }
+
+    .transparent-input-file {
+        position: absolute;
+        top: 0;
+        left: 0;
+        width: 100%;
+        height: 100%;
+        opacity: 0;
+        cursor: pointer;
+        z-index: 2;
+    }
 </style>

+ 11 - 0
Platform/AI.Platform.Page/Pages/Site/Model/SiteModel.cs

@@ -97,6 +97,11 @@ namespace AI.Platform.Page.Pages.Site.Model
         [Required(ErrorMessage = "请填写联系方式")]
         public string Contact { get; set; }
 
+        /// <summary>
+        /// 上传文件大小
+        /// </summary>
+        public long MaxSize { get; set; } = 31457280; //30M
+
         public SiteEntity ToCompany()
         {
             SiteEntity siteEntity = new SiteEntity()
@@ -105,6 +110,7 @@ namespace AI.Platform.Page.Pages.Site.Model
                 Name = Name,
                 Address = Address,
                 Contact = Contact,
+                MaxSize = MaxSize,
                 CreateTime = DateTime.Now
             };
 
@@ -132,6 +138,11 @@ namespace AI.Platform.Page.Pages.Site.Model
         /// 站名
         /// </summary>
         public string Name { get; set; }
+
+        /// <summary>
+        /// 上传文件大小
+        /// </summary>
+        public long MaxSize { get; set; }
     }
 
     /// <summary>

+ 3 - 3
Platform/AI.Platform.Page/Pages/Site/Screen.razor.cs

@@ -150,8 +150,8 @@ public partial class Screen
             .LeftJoin<SiteEntity>((screen, site) => screen.SiteId == site.Id);
 
         query = query
-            .WhereIF(filterData.siteName.IsNotNullOrEmpty(),(screent,site) => site.Name.Contains(filterData.siteName))
-            .WhereIF(filterData.sn.IsNotNullOrEmpty(),it => it.sn.Contains(filterData.sn));
+            .WhereIF(filterData.siteName.IsNotNullOrEmpty(),(screen, site) => site.Name.Contains(filterData.siteName))
+            .WhereIF(filterData.sn.IsNotNullOrEmpty(), (screen, site) => screen.sn.Contains(filterData.sn));
 
         Total = await query.CountAsync();
 
@@ -187,7 +187,7 @@ public partial class Screen
     /// </summary>
     private void HandleReset()
     {
-
+        filterData = new();
     }
 
     private async Task searchSitesAsync()

+ 1 - 1
Platform/AI.Platform.Page/Pages/Site/Site.razor.cs

@@ -231,7 +231,7 @@ public partial class Site
     /// </summary>
     private void HandleReset()
     {
-
+        filterData = new();
     }
 
     private async Task searchSitesAsync()

+ 15 - 4
Platform/AI.Platform.Service/FileService.cs

@@ -10,6 +10,7 @@ using System.Net;
 using System;
 using AI.Platform.Service.Output;
 using Microsoft.AspNetCore.Http.HttpResults;
+using AI.Platform.Core.Entity.Site;
 
 namespace AI.Platform.Service;
 
@@ -20,10 +21,12 @@ public class FileService : BaseService
     /// 
     /// </summary>
     private readonly IHttpContextAccessor _contextAccessor;
+    private readonly SqlSugarRepository<SiteEntity> _siteReponsitory;
 
-    public FileService(IHttpContextAccessor contextAccessor)
+    public FileService(IHttpContextAccessor contextAccessor, SqlSugarRepository<SiteEntity> siteReponsitory)
     {
         _contextAccessor = contextAccessor;
+        _siteReponsitory = siteReponsitory;
     }
 
     /// <summary>
@@ -75,8 +78,8 @@ public class FileService : BaseService
     /// <param name="classification"></param>
     /// <returns></returns>
     [HttpPost]
-    [RequestSizeLimit(307_200_000)]
-    public async Task<MediaFileUploadOutput> UploadMedia(IFormFile file)
+    //[RequestSizeLimit(307_200_000)]
+    public async Task<MediaFileUploadOutput> UploadMedia(IFormFile file,long siteId)
     {
        
         if (file == null || file.Length <= 0)
@@ -97,10 +100,18 @@ public class FileService : BaseService
         // 生成文件名
         var id = Guid.NewGuid().ToString().ToUpper().Replace("-", "");
         var fileName = $"{id}_{file.FileName}";
+
+        string siteName = "未知站点";
+        SiteEntity siteEntity = await _siteReponsitory.AsQueryable().Where(it => it.Id == siteId).FirstAsync();
+        if(siteEntity != null)
+        {
+            siteName = siteEntity.Name;
+        }
+
         // 获取当前日期
         var currentDate = DateTime.Now;
         // 构建目录路径
-        var directoryPath = Path.Combine("wwwroot", "madia", currentDate.ToString("MM"), currentDate.ToString("dd"));
+        var directoryPath = Path.Combine("wwwroot", "madia", siteName);
         // 创建目录
         if (!Directory.Exists(directoryPath))
         {

+ 3 - 0
Platform/AI.Platform.Tool/Entity/Site/SiteEntity.cs

@@ -19,5 +19,8 @@ namespace AI.Platform.Core.Entity.Site
 
         [SugarColumn(ColumnDescription = "联系方式")]
         public string Contact {  get; set; }
+
+        [SugarColumn(ColumnDescription = "上传文件大小")]
+        public long MaxSize { get; set; }
     }
 }

+ 1 - 0
Platform/AI.Platform.Tool/Util/Global.cs

@@ -49,6 +49,7 @@ public static class Global
     /// 媒体文件上传地址
     /// </summary>
     public static string MediaUploadUrl { get { return Setting.Get<string>("MediaUpload:Url"); } }
+
     /// <summary>
     /// 富文本apikey
     /// </summary>

+ 2 - 0
Platform/AI.Platform.Web/AI.Platform.Web.csproj

@@ -30,6 +30,8 @@
   <ItemGroup>
     <Folder Include="wwwroot\madia\01\" />
     <Folder Include="wwwroot\madia\01\20\" />
+    <Folder Include="wwwroot\madia\01\28\" />
+    <Folder Include="wwwroot\madia\01\29\" />
   </ItemGroup>
 
 </Project>

+ 11 - 11
Platform/AI.Platform.Web/AI.Platform.Web.csproj.user

@@ -1,12 +1,12 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
-    <DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
-  </PropertyGroup>
-  <PropertyGroup>
-    <ActiveDebugProfile>http</ActiveDebugProfile>
-    <NameOfLastUsedPublishProfile>C:\cw\Code\车载机\EasyTemplate.Blazor.Web-master\EasyTemplate.Blazor.Web-master\EasyTemplate.Blazor.Web\Properties\PublishProfiles\FolderProfile.pubxml</NameOfLastUsedPublishProfile>
-    <Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
-    <Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
-  </PropertyGroup>
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
+    <DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
+  </PropertyGroup>
+  <PropertyGroup>
+    <ActiveDebugProfile>http</ActiveDebugProfile>
+    <NameOfLastUsedPublishProfile>FolderProfile</NameOfLastUsedPublishProfile>
+    <Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
+    <Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
+  </PropertyGroup>
 </Project>

+ 4 - 2
Platform/AI.Platform.Web/Program.cs

@@ -10,14 +10,16 @@ WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(args)
 //设置请求大小最大值,用于上传文件
 webApplicationBuilder.WebHost.ConfigureKestrel(options =>
  {
-     options.Limits.MaxRequestBodySize = 307_200_000; //300M
+     options.Limits.MaxRequestBodySize = 314_572_800; //300M
  });
 webApplicationBuilder.Services.Configure<FormOptions>(options =>
 {
-    options.MultipartBodyLengthLimit = 307_200_000; //300M
+    options.MultipartBodyLengthLimit = 314_572_800; //300M
 });
 
 webApplicationBuilder.Services.AddScoped<AuthService>();
+webApplicationBuilder.Services.AddScoped<HttpClient>();
+webApplicationBuilder.Services.AddScoped<MessageService>();
 
 webApplicationBuilder.RegistService().RegistApp();