From 8b613a5275e6fe23b91f65cc6a7fba720ae4d7ef Mon Sep 17 00:00:00 2001
From: 移动系统liao <liaoxujun@qq.com>
Date: 星期二, 18 二月 2025 11:10:35 +0800
Subject: [PATCH] 完成阿里云本地上传token生成,实现小程序本地上传

---
 cylsg/EzUpFile/EzFileUploadService.cs                        |  247 +++++++++++++++++++++++++++++++++++++++--
 cylsg/EzUpFile/EzUpFile.csproj                               |    4 
 cylsg/cylsg.Model/ECTEModel/OaWorkPlan.cs                    |   14 +
 ali本地上key和其他配置.txt                                           |   15 ++
 cylsg/EzUpFile/UpFileController.cs                           |   11 +
 cylsg/cylsg.Application/CyOS/CyOSBaoXiaoZHuGuanController.cs |   25 +++
 cylsg/cylsg.Application/CyOS/CyOSStaffController.cs          |    1 
 cylsg/EzUpFile/IEzFileUploadService.cs                       |    6 +
 8 files changed, 304 insertions(+), 19 deletions(-)

diff --git "a/ali\346\234\254\345\234\260\344\270\212key\345\222\214\345\205\266\344\273\226\351\205\215\347\275\256.txt" "b/ali\346\234\254\345\234\260\344\270\212key\345\222\214\345\205\266\344\273\226\351\205\215\347\275\256.txt"
new file mode 100644
index 0000000..97e7c83
--- /dev/null
+++ "b/ali\346\234\254\345\234\260\344\270\212key\345\222\214\345\205\266\344\273\226\351\205\215\347\275\256.txt"
@@ -0,0 +1,15 @@
+	
+AccessKey ID:  LTAI5tKegnEbaSRPFRwDxeFd
+ AccessKey Secret:9Hv6VYgWhpDHCMkwMLHiqF6ihusjdl
+
+ weixinupdata@1299465997752835.onaliyun.com
+
+
+
+ 
+ 鐢ㄦ埛鐧诲綍鍚嶇О weixinupdata@1299465997752835.onaliyun.com
+AccessKey ID LTAI5tKegnEbaSRPFRwDxeFd
+AccessKey Secret 9Hv6VYgWhpDHCMkwMLHiqF6ihusjdl
+
+     RoleArn = "acs:ram::1299465997752835:role/weixinupdatarl",
+     RoleSessionName = "weixinupdataRl",
\ No newline at end of file
diff --git a/cylsg/EzUpFile/EzFileUploadService.cs b/cylsg/EzUpFile/EzFileUploadService.cs
index e48e3c8..568e928 100644
--- a/cylsg/EzUpFile/EzFileUploadService.cs
+++ b/cylsg/EzUpFile/EzFileUploadService.cs
@@ -1,5 +1,7 @@
 锘�
+using Aliyun.Acs.Core.Exceptions;
 using Aliyun.OSS;
+
 using Aliyun.OSS.Util;
 using cylsg.utility;
 using cylsg.utility.Extend;
@@ -10,14 +12,16 @@
 using Microsoft.AspNetCore.Http;
 
 using SqlSugar;
-using System;
-using System.Buffers.Text;
 using System.Drawing;
 using System.Globalization;
-using System.Security.Policy;
+using System.Security.Cryptography;
+using System.Text;
+using Tea;
 using TencentCloud.Ocr.V20181119.Models;
-using TencentCloud.Teo.V20220901.Models;
+
 using Task = System.Threading.Tasks.Task;
+using Newtonsoft.Json;
+using static AlibabaCloud.SDK.Sts20150401.Models.AssumeRoleResponseBody;
 namespace EzUpFile
 {
     /// <summary>
@@ -29,12 +33,12 @@
         private readonly HttpRequest? _request;
         private readonly ISqlSugarClient _sqlSugarClient;
         private readonly ITencentCloudService _tcs;
-        public EzFileUploadService(IHttpContextAccessor httpContext, ISqlSugarClient sqlSugarClient,ITencentCloudService tencentCloudService)
+        public EzFileUploadService(IHttpContextAccessor httpContext, ISqlSugarClient sqlSugarClient, ITencentCloudService tencentCloudService)
         {
 
             _request = httpContext.HttpContext?.Request ?? null;
             _sqlSugarClient = sqlSugarClient;
-            _tcs= tencentCloudService;
+            _tcs = tencentCloudService;
         }
 
         /// <summary>
@@ -178,7 +182,7 @@
                 throw Oops.Oh(ex.Message);
             }
 
-            //杩斿洖缁橴Editor鐨勬彃鍏ョ紪杈戝櫒鐨勫浘鐗囩殑src
+
 
             return App.Configuration["FileUploadOptions:AliOSSSaveBaseUrl"] + filePath;
         }
@@ -349,7 +353,7 @@
                 catch (Exception e)
                 {
 
-                    throw Oops.Oh(e.Message+"鑵捐浜戯紝鎴栬�呴樋閲屼簯鎿嶄綔閿欒");
+                    throw Oops.Oh(e.Message + "鑵捐浜戯紝鎴栬�呴樋閲屼簯鎿嶄綔閿欒");
                 }
             }
             catch (Exception e)
@@ -426,7 +430,7 @@
         }
 
 
-        public async Task<(bool,string)> IaiAddPerso(string CoredID,string Name,int PersonGender)
+        public async Task<(bool, string)> IaiAddPerso(string CoredID, string Name, int PersonGender)
         {
             try
             {
@@ -466,12 +470,12 @@
                 var arr = ms.ToArray();
                 string img64 = Convert.ToBase64String(arr);
 
-                bool  info = false;
+                bool info = false;
                 string url = "";
 
                 try
                 {
-                    info =  _tcs.IaiAddPerso(img64, CoredID, Name, PersonGender);
+                    info = _tcs.IaiAddPerso(img64, CoredID, Name, PersonGender);
 
                     url = await UploadFilesFByBase64(img64);
 
@@ -490,7 +494,7 @@
                 throw Oops.Oh(e.Message);
             }
         }
-/// <inheritdoc/>
+        /// <inheritdoc/>
 
         public async Task<(bool, string)> IaiAddPerso(string imgBase64, string CoredID, string Name, int PersonGender)
         {
@@ -527,5 +531,224 @@
 
 
         #endregion
+
+        #region 鏈湴涓婁紶浜戞湇鍔″櫒鍑瘉璁$畻
+
+
+        public Dictionary<string, string> GetToken1()
+        {
+
+            var dir = DateTime.Now.ToString("yyyyMMdd") + "/";
+            // 鏋勯�燨ssClient瀹炰緥銆� endpoint 鏍煎紡:https://oss-cn-beijing.aliyuncs.com
+            //  var ossClient = new OssClient( App.Configuration["FileUploadOptions:AliOSSSaveBaseUrl"], App.Configuration["FileUploadOptions:AliOSSAccessKeyID"], App.Configuration["FileUploadOptions:AliOSSAccessKeySecret"]);
+            var rt = GetSTSToken();
+
+
+
+
+            String securityToken = rt.AccessKeySecret;   //鑾峰彇Token
+            var config = new PolicyConditions();
+
+            config.AddConditionItem(PolicyConditions.CondContentLengthRange, 1, 1024L * 1024 * 1024 * 5);// 鏂囦欢澶у皬鑼冨洿锛氬崟浣峛yte
+            config.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, dir);
+            //鎹呭悕
+            config.AddConditionItem("bucket", App.Configuration["FileUploadOptions:AliOSSBucketName"]);
+            config.AddConditionItem("x-oss-signature-version", "OSS4-HMAC-SHA256");
+            config.AddConditionItem("x-oss-security-token", securityToken);
+            //     //璇锋眰鏃堕棿
+            config.AddConditionItem("x-oss-date", DateTime.Now.ToString("yyyyMMdd'T'HHmmss'Z'"));
+            config.AddConditionItem("x-oss-credential", App.Configuration["FileUploadOptions:AliOSSAccessKeyID"] + "/" + DateTime.Now.ToString("yyyyMMdd") + "/cn-chengdu/oss/aliyun_v4_request");
+            var expire = DateTimeOffset.Now.AddMinutes(30);// 杩囨湡鏃堕棿
+
+            // 鐢熸垚 Policy锛屽苟杩涜 Base64 缂栫爜
+            //  var policy = ossClient.GeneratePostPolicy(expire.LocalDateTime, config);
+            //   var policyBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(policy));
+
+            // 璁$畻绛惧悕
+            var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(App.Configuration["FileUploadOptions:AliOSSAccessKeySecret"]));
+            //    var bytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(policyBase64));
+            //  var sign = Convert.ToBase64String(bytes);
+
+            return new Dictionary<string, string>();
+        }
+
+
+
+
+
+
+        public static AlibabaCloud.SDK.Sts20150401.Client CreateClient()
+        {
+            // 宸ョ▼浠g爜娉勯湶鍙兘浼氬鑷� AccessKey 娉勯湶锛屽苟濞佽儊璐﹀彿涓嬫墍鏈夎祫婧愮殑瀹夊叏鎬с�備互涓嬩唬鐮佺ず渚嬩粎渚涘弬鑰冦��
+            // 寤鸿浣跨敤鏇村畨鍏ㄧ殑 STS 鏂瑰紡锛屾洿澶氶壌鏉冭闂柟寮忚鍙傝锛歨ttps://help.aliyun.com/document_detail/378671.html銆�
+            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
+            {
+                // 蹇呭~锛岃纭繚浠g爜杩愯鐜璁剧疆浜嗙幆澧冨彉閲� ALIBABA_CLOUD_ACCESS_KEY_ID銆�
+                AccessKeyId = "LTAI5tKegnEbaSRPFRwDxeFd",
+                // 蹇呭~锛岃纭繚浠g爜杩愯鐜璁剧疆浜嗙幆澧冨彉閲� ALIBABA_CLOUD_ACCESS_KEY_SECRET銆�
+                AccessKeySecret = "9Hv6VYgWhpDHCMkwMLHiqF6ihusjdl",
+            };
+            // Endpoint 璇峰弬鑰� https://api.aliyun.com/product/Sts
+            config.Endpoint = "sts.cn-chengdu.aliyuncs.com";
+            return new AlibabaCloud.SDK.Sts20150401.Client(config);
+        }
+
+        /// <summary>
+        /// 鑾峰彇涓存椂鍑瘉
+        /// </summary>
+        public static AssumeRoleResponseBodyCredentials GetSTSToken()
+        {
+            AlibabaCloud.SDK.Sts20150401.Client client = CreateClient();
+            AlibabaCloud.SDK.Sts20150401.Models.AssumeRoleRequest assumeRoleRequest = new AlibabaCloud.SDK.Sts20150401.Models.AssumeRoleRequest
+            {
+                Policy = "{\"Statement\": [{\"Action\": [\"*\"],\"Effect\": \"Allow\",\"Resource\": [\"*\"]}],\"Version\":\"1\"}",
+                DurationSeconds = 3600,
+                RoleArn = "acs:ram::1299465997752835:role/weixinupdatarl",
+                RoleSessionName = "weixinupdataRl",
+            };
+            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
+            try
+            {
+                // 澶嶅埗浠g爜杩愯璇疯嚜琛屾墦鍗� API 鐨勮繑鍥炲��
+                var data = client.AssumeRoleWithOptions(assumeRoleRequest, runtime);
+                if (data.StatusCode == 200)
+                {
+
+                    return data.Body?.Credentials;
+                }
+                throw Oops.Oh("闃块噷浜戣幏鍙栦复鏃跺嚟璇侀敊璇�");
+            }
+            catch (TeaException error)
+            {
+
+                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
+                throw;
+            }
+            catch (Exception _error)
+            {
+                TeaException error = new TeaException(new Dictionary<string, object>
+                {
+                    { "message", _error.Message }
+                });
+
+                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
+                throw error;
+            }
+        }
+        /// <summary>
+        /// 
+        /// </summary>
+        /// <returns></returns>
+        public Dictionary<string, string> GetToken()
+        {
+            // 鑾峰彇鐜鍙橀噺
+
+            string regionId = "cn-chengdu";
+            string roleSessionName = "weixinupdataRl";
+
+
+
+
+
+
+
+            // 瀹氫箟STS涓存椂璁块棶鍑瘉鍙橀噺
+            string stsAccessKeyId = null;
+            string stsSecretAccessKey = null;
+            string securityToken = null;
+
+            try
+            {
+                var rt = GetSTSToken();
+
+                stsAccessKeyId = rt.AccessKeyId;
+                stsSecretAccessKey = rt.AccessKeySecret;
+                securityToken = rt.SecurityToken;
+            }
+            catch (ServerException e)
+            {
+                throw;
+            }
+            catch (ClientException e)
+            {
+                throw;
+            }
+
+            // 鏍煎紡鍖栬姹傛棩鏈�
+            DateTimeOffset now = DateTimeOffset.UtcNow;
+            string dtObj1 = now.ToString("yyyyMMdd'T'HHmmss'Z'", CultureInfo.InvariantCulture);
+            string dtObj2 = now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
+            string expirationTime = now.AddHours(3).ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
+
+            // 鍒涘缓policy
+            Dictionary<string, object> policy = new Dictionary<string, object>
+        {
+            { "expiration", expirationTime },
+            { "conditions", new List<object>
+                {
+                    new Dictionary<string, string> { { "bucket", App.Configuration["FileUploadOptions:AliOSSBucketName"] } }, // 璇峰皢<bucketname>鏇挎崲涓烘偍鐨勫疄闄匓ucket鍚嶇О
+                    new Dictionary<string, string> { { "x-oss-signature-version", "OSS4-HMAC-SHA256" } },
+                    new Dictionary<string, string> { { "x-oss-credential", $"{stsAccessKeyId}/{dtObj2}/{regionId}/oss/aliyun_v4_request" } }, // 璇峰皢<cn-hangzhou>鏇挎崲涓烘偍鐨勫疄闄匓ucket鎵�澶勫湴鍩燂紝渚嬪鍖椾含鍦板煙涓猴細cn-beijing
+                    new Dictionary<string, string> { { "x-oss-security-token", securityToken } },
+                    new Dictionary<string, string> { { "x-oss-date", dtObj1 } }
+                }
+            }
+        };
+
+            string jsonPolicy = JsonConvert.SerializeObject(policy);
+
+            // 鏋勯�犲緟绛惧悕瀛楃涓诧紙StringToSign锛�
+            string stringToSign = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonPolicy));
+
+            // 璁$畻SigningKey
+            byte[] dateKey = HmacSha256("aliyun_v4" + stsSecretAccessKey, dtObj2);
+            byte[] dateRegionKey = HmacSha256(dateKey, regionId); // 璇峰皢<cn-hangzhou>鏇挎崲涓烘偍鐨勫疄闄匓ucket鎵�澶勫湴鍩燂紝渚嬪鍖椾含鍦板煙涓猴細cn-beijing
+            byte[] dateRegionServiceKey = HmacSha256(dateRegionKey, "oss");
+            byte[] signingKey = HmacSha256(dateRegionServiceKey, "aliyun_v4_request");
+
+            // 璁$畻Signature
+            byte[] result = HmacSha256(signingKey, stringToSign);
+            string signature = BitConverter.ToString(result).Replace("-", "").ToLower();
+
+            Dictionary<string, string> messageMap = new Dictionary<string, string>
+        {
+            { "security_token", securityToken },
+            { "signature", signature },
+            { "x_oss_date", dtObj1 },
+            { "x_oss_credential", $"{stsAccessKeyId}/{dtObj2}/{regionId}/oss/aliyun_v4_request" }, // 璇峰皢<cn-hangzhou>鏇挎崲涓烘偍鐨勫疄闄匓ucket鎵�澶勫湴鍩燂紝渚嬪鍖椾含鍦板煙涓猴細cn-beijing
+            { "x_oss_signature_version", "OSS4-HMAC-SHA256" },
+            { "policy", stringToSign }
+        };
+
+            // 鎵撳嵃杩斿洖鑷冲鎴风鐨勭鍚嶄俊鎭�
+            return messageMap;
+        }
+
+
+
+        private static byte[] HmacSha256(byte[] key, string message)
+        {
+            using (HMACSHA256 hmac = new HMACSHA256(key))
+            {
+                return hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
+            }
+        }
+
+        private static byte[] HmacSha256(string key, string message)
+        {
+            using (HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
+            {
+                return hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
+            }
+        }
+
+
+
+        #endregion
     }
+
+
+
+
 }
+
diff --git a/cylsg/EzUpFile/EzUpFile.csproj b/cylsg/EzUpFile/EzUpFile.csproj
index d21d20d..0ae9560 100644
--- a/cylsg/EzUpFile/EzUpFile.csproj
+++ b/cylsg/EzUpFile/EzUpFile.csproj
@@ -8,7 +8,11 @@
   </PropertyGroup>
 
   <ItemGroup>
+    <PackageReference Include="AlibabaCloud.SDK.Sts20150401" Version="1.1.4" />
+    <PackageReference Include="Aliyun.Acs.Core" Version="1.0.1" />
+    <PackageReference Include="Aliyun.Acs.Sts" Version="1.0.1" />
     <PackageReference Include="Aliyun.OSS.SDK.NetCore" Version="2.14.1" />
+    <PackageReference Include="Utf8Json" Version="1.3.7" />
   </ItemGroup>
 
   <ItemGroup>
diff --git a/cylsg/EzUpFile/IEzFileUploadService.cs b/cylsg/EzUpFile/IEzFileUploadService.cs
index dbf822d..580272a 100644
--- a/cylsg/EzUpFile/IEzFileUploadService.cs
+++ b/cylsg/EzUpFile/IEzFileUploadService.cs
@@ -59,6 +59,12 @@
         /// <returns></returns>
         Task<(bool, string)> IaiAddPerso(string imgBase64, string CoredID, string Name, int PersonGender);
 
+        /// <summary>
+        /// 
+        /// </summary>
+        /// <returns></returns>
+        Dictionary<string, string> GetToken();
+
     }
 
 
diff --git a/cylsg/EzUpFile/UpFileController.cs b/cylsg/EzUpFile/UpFileController.cs
index 108fdf1..ec28556 100644
--- a/cylsg/EzUpFile/UpFileController.cs
+++ b/cylsg/EzUpFile/UpFileController.cs
@@ -5,6 +5,7 @@
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc.RazorPages;
 using Microsoft.IdentityModel.Abstractions;
+using StackExchange.Profiling.Internal;
 using System;
 using System.Collections.Generic;
 using System.Linq;
@@ -21,8 +22,16 @@
     [ApiDescriptionSettings("FileUpdata")]    
     public class UpFileController
     {
+        /// <summary>
+        /// 鑾峰彇鏂囦欢 涓婁紶token
+        /// </summary>  
+        /// <returns></returns>
+        [HttpGet]
 
-
+        public Dictionary<string, string> GetToken([FromServices] IEzFileUploadService fileUploadService)
+        {
+            return fileUploadService.GetToken();
+        }
         /// <summary>
         /// 涓婁紶韬唤璇佷俊鎭�
         /// </summary>   
diff --git a/cylsg/cylsg.Application/CyOS/CyOSBaoXiaoZHuGuanController.cs b/cylsg/cylsg.Application/CyOS/CyOSBaoXiaoZHuGuanController.cs
index 39e60fe..5ccdc56 100644
--- a/cylsg/cylsg.Application/CyOS/CyOSBaoXiaoZHuGuanController.cs
+++ b/cylsg/cylsg.Application/CyOS/CyOSBaoXiaoZHuGuanController.cs
@@ -25,8 +25,29 @@
             _OAServices = oaservices;
             _SugarClient = sugarClient.AsTenant().GetConnection("ECTESTOADB");
         }
+        /// <summary>
+        /// 鏌ヨ
+        /// </summary>
+        /// <returns></returns>
+        [HttpGet]
+        [AllowAnonymous]
+        public async Task<List<OaWorkPlan>> gettest()
+        {
+            var datal = await _SugarClient.Queryable<OaWorkPlan>().Where(x=>x.PlanType==3&&x.PlanDataType==17)
+         .Select(x => new OaWorkPlan
+         {
+             OaWorkPlanShenpi = SqlFunc.Subqueryable<OaWorkPlanShenpi>().Where(y => y.OA_WorkPlanId == x.Keyid).First()
+         }, true).MergeTable()
+         .OrderBy(z => z.OaWorkPlanShenpi.ApprovalTime).ToListAsync();
+            return datal;
+            var data2 = await _SugarClient.Queryable<OaWorkPlan>()
+                .Select(x => new OaWorkPlan
+                {
+                    SentStaff = SqlFunc.Subqueryable<OaStaff>().Where(y => y.MemberId == x.SentStaffId).First()
+                }, true).MergeTable()
+                .OrderBy(y => y.SentStaff.MemberId).ToListAsync();
 
-
+        }
         /// <summary>
         ///  鏌ヨ
         /// </summary>
@@ -91,7 +112,7 @@
             RefAsync<int> totle = 0;
 
             //寮哄埗澧炲姞鍛樺伐杩囨护
-
+   
             var data = await _SugarClient.Queryable<OaWorkPlan>().Includes(x=>x.Depart)
                     .Includes(x=>x.OaWorkPlanShenpis.Where(y=>y.ApprovalStaffId==Permissions.MemberId&&y.Buzhou==1).ToList())
                     .Where(SearchList).OrderByDescending(x => x.PlanStartTime).Mapper(
diff --git a/cylsg/cylsg.Application/CyOS/CyOSStaffController.cs b/cylsg/cylsg.Application/CyOS/CyOSStaffController.cs
index 705d511..a888020 100644
--- a/cylsg/cylsg.Application/CyOS/CyOSStaffController.cs
+++ b/cylsg/cylsg.Application/CyOS/CyOSStaffController.cs
@@ -42,6 +42,7 @@
         [HttpPost]
         public async Task<WorekPlandto> getplanelist(SearchOaWorekPlan param)
         {
+            
             if(! await CheckRols())
             {
                 throw Oops.Oh("娌℃湁鏉冮檺");
diff --git a/cylsg/cylsg.Model/ECTEModel/OaWorkPlan.cs b/cylsg/cylsg.Model/ECTEModel/OaWorkPlan.cs
index 84d9ea8..e4110a7 100644
--- a/cylsg/cylsg.Model/ECTEModel/OaWorkPlan.cs
+++ b/cylsg/cylsg.Model/ECTEModel/OaWorkPlan.cs
@@ -139,10 +139,16 @@
         /// </summary>       
         [Navigate(NavigateType.OneToMany,  nameof(OaWorkPlanShenpi.OA_WorkPlanId), nameof(Keyid))]
         public List<OaWorkPlanShenpi>? OaWorkPlanShenpis {  get; set; }
-            /// <summary>
-            /// 瀹℃牳鏃堕棿
-            /// </summary>
-            [SugarColumn(ColumnName = "ApprovalTime")]
+
+        /// <summary>
+        /// 鐏垫椂
+        /// </summary>
+        [SugarColumn(IsIgnore =true)]       
+        public OaWorkPlanShenpi? OaWorkPlanShenpi { get; set; }
+        /// <summary>
+        /// 瀹℃牳鏃堕棿
+        /// </summary>
+        [SugarColumn(ColumnName = "ApprovalTime")]
             public DateTime? ApprovalTime { get; set; }
 
             /// <summary>

--
Gitblit v1.9.1