diff --git a/CoreCms.Net.Configuration/GlobalEnumVars.cs b/CoreCms.Net.Configuration/GlobalEnumVars.cs index 05be22ef6e6e13c23f1c19af1a872f4cc5331bbe..bc9e76b338b22d9bb6332b0210550d52a3cc59f3 100644 --- a/CoreCms.Net.Configuration/GlobalEnumVars.cs +++ b/CoreCms.Net.Configuration/GlobalEnumVars.cs @@ -105,6 +105,8 @@ namespace CoreCms.Net.Configuration AliYunOSS = 1, [Description("腾讯云COS")] QCloudOSS = 2, + [Description("七牛云KoDo")] + QiNiuKoDo = 3, } #endregion diff --git a/CoreCms.Net.Configuration/SystemSettingConstVars.cs b/CoreCms.Net.Configuration/SystemSettingConstVars.cs index ab76046c8d1bd3138244d736b77885f3bda0529f..15edd248a1fc329c86dca25736d7a6a5196815ce 100644 --- a/CoreCms.Net.Configuration/SystemSettingConstVars.cs +++ b/CoreCms.Net.Configuration/SystemSettingConstVars.cs @@ -649,6 +649,11 @@ namespace CoreCms.Net.Configuration /// public static readonly string FilesStorageAliYunBucketName = "filesStorageAliYunBucketName"; + /// + /// 七牛云桶名称 + /// + public static readonly string FilesStorageQiNiuBucketName = "filesStorageQiNiuBucketName"; + } diff --git a/CoreCms.Net.Configuration/SystemSettingDictionary.cs b/CoreCms.Net.Configuration/SystemSettingDictionary.cs index 0c595f7107d3b8a45a5446f22d590f7d1b07c196..688738a3f6e25e5df5ded4b3099e605148ebcc8b 100644 --- a/CoreCms.Net.Configuration/SystemSettingDictionary.cs +++ b/CoreCms.Net.Configuration/SystemSettingDictionary.cs @@ -192,6 +192,9 @@ namespace CoreCms.Net.Configuration di.Add(SystemSettingConstVars.FilesStorageAliYunEndpoint, new DictionaryKeyValues() { sKey = "阿里云节点", sValue = "https://oss-cn-shenzhen.aliyuncs.com" }); di.Add(SystemSettingConstVars.FilesStorageAliYunBucketName, new DictionaryKeyValues() { sKey = "阿里云桶名称", sValue = "CoreShop" }); + di.Add(SystemSettingConstVars.FilesStorageQiNiuBucketName, new DictionaryKeyValues() { sKey = "七牛云桶名称", sValue = "CoreShop" }); + + return di; } diff --git a/CoreCms.Net.IServices/Com/IToolsServices.cs b/CoreCms.Net.IServices/Com/IToolsServices.cs index 0741d8076a6808b7e573f581520b8d3b57ff4359..92dc1aa91cc835b1eea9fdbb3b2cc601aa21eb80 100644 --- a/CoreCms.Net.IServices/Com/IToolsServices.cs +++ b/CoreCms.Net.IServices/Com/IToolsServices.cs @@ -9,8 +9,11 @@ ***********************************************************************/ using System; +using System.IO; using System.Threading.Tasks; using CoreCms.Net.Model.Entities; +using CoreCms.Net.Model.ViewModels.Options; +using Microsoft.AspNetCore.Http; namespace CoreCms.Net.IServices { @@ -35,5 +38,62 @@ namespace CoreCms.Net.IServices Task IllegalWordsContainsAny(string oldString); + #region FIle文件上传处理 + /// + /// 本地上传(File) + /// + /// + Task UpLoadFileForLocalStorage(FilesStorageOptions options, string fileExt, IFormFile file); + + /// + /// AliYunOSS-阿里云上传方法(File) + /// + /// + Task UpLoadFileForAliYunOSS(FilesStorageOptions options, string fileExt, IFormFile file); + + /// + /// QCloudOSS-腾讯云存储上传方法(File) + /// + /// + Task UpLoadFileForQCloudOSS(FilesStorageOptions options, string fileExt, IFormFile file); + /// + /// QiNiuKoDo-七牛云存储上传方法(File) + /// + /// + Task UpLoadFileForQiNiuKoDo(FilesStorageOptions options, string fileExt, IFormFile file); + #endregion + + + + #region Base64文件上传处理 + /// + /// 本地上传(Base64) + /// + /// + string UpLoadBase64ForLocalStorage(FilesStorageOptions options, MemoryStream memStream); + + /// + /// AliYunOSS-阿里云上传方法(Base64) + /// + /// + Task UpLoadBase64ForAliYunOSS(FilesStorageOptions options, MemoryStream memStream); + + /// + /// QCloudOSS-腾讯云存储上传方法(Base64) + /// + /// + string UpLoadBase64ForQCloudOSS(FilesStorageOptions options, byte[] bytes); + + /// + /// QiNiuKoDo-七牛云存储上传方法(Base64) + /// + /// + string UpLoadBase64ForQiNiuKoDo(FilesStorageOptions options, byte[] bytes); + + #endregion + + + + } } \ No newline at end of file diff --git a/CoreCms.Net.IServices/CoreCms.Net.IServices.csproj b/CoreCms.Net.IServices/CoreCms.Net.IServices.csproj index cef95ee77910964a278585eb71f362ba0b2b59f4..d54c78d3e90f23ae9611925c1a10c8bac666bb99 100644 --- a/CoreCms.Net.IServices/CoreCms.Net.IServices.csproj +++ b/CoreCms.Net.IServices/CoreCms.Net.IServices.csproj @@ -4,6 +4,10 @@ net5.0 + + + + diff --git a/CoreCms.Net.Model/ViewModels/Options/FilesStorageOptions.cs b/CoreCms.Net.Model/ViewModels/Options/FilesStorageOptions.cs index 6f72956ad57ac5d01ac84adf700a56f9c2c82dee..305fc198df2fece44ee508cd6b993755cba95d04 100644 --- a/CoreCms.Net.Model/ViewModels/Options/FilesStorageOptions.cs +++ b/CoreCms.Net.Model/ViewModels/Options/FilesStorageOptions.cs @@ -41,6 +41,10 @@ namespace CoreCms.Net.Model.ViewModels.Options /// public string TencentBucketName { get; set; } + /// + /// 存储桶名称(七牛云) + /// + public string QiNiuBucketName { get; set; } /// /// 授权账户 diff --git a/CoreCms.Net.Services/Com/ToolsServices.cs b/CoreCms.Net.Services/Com/ToolsServices.cs index e6791d59ff83eb9dc312a7f40f0882794a2f2e28..6351fa283be909db042572717377d0c8cec0c29e 100644 --- a/CoreCms.Net.Services/Com/ToolsServices.cs +++ b/CoreCms.Net.Services/Com/ToolsServices.cs @@ -10,16 +10,27 @@ using System; +using System.Drawing; +using System.Globalization; using System.IO; using System.Threading.Tasks; +using Aliyun.OSS; +using Aliyun.OSS.Util; using CoreCms.Net.Caching.Manual; using CoreCms.Net.Configuration; using CoreCms.Net.IRepository; using CoreCms.Net.IRepository.UnitOfWork; using CoreCms.Net.IServices; using CoreCms.Net.Model.Entities; +using CoreCms.Net.Model.ViewModels.Options; +using CoreCms.Net.Model.ViewModels.UI; +using COSXML; +using COSXML.Auth; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.FileProviders; +using Qiniu.Storage; +using Qiniu.Util; using ToolGood.Words; namespace CoreCms.Net.Services @@ -29,11 +40,14 @@ namespace CoreCms.Net.Services /// public class ToolsServices : IToolsServices { - private IWebHostEnvironment _hostEnvironment; + private readonly IWebHostEnvironment _hostEnvironment; + private readonly IWebHostEnvironment _webHostEnvironment; - public ToolsServices(IWebHostEnvironment hostEnvironment) + + public ToolsServices(IWebHostEnvironment hostEnvironment, IWebHostEnvironment webHostEnvironment) { _hostEnvironment = hostEnvironment; + _webHostEnvironment = webHostEnvironment; } @@ -97,5 +111,317 @@ namespace CoreCms.Net.Services return bl; } + + + #region 本地上传方法(File) + /// + /// 本地上传方法(File) + /// + /// + /// + /// + /// + public async Task UpLoadFileForLocalStorage(FilesStorageOptions options, string fileExt, IFormFile file) + { + + var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; + var today = DateTime.Now.ToString("yyyyMMdd"); + + var saveUrl = options.Path + today + "/"; + var dirPath = _webHostEnvironment.WebRootPath + saveUrl; + if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); + var filePath = dirPath + newFileName; + var fileUrl = saveUrl + newFileName; + + string bucketBindDomain = AppSettingsConstVars.AppConfigAppUrl; + + await using (var fs = System.IO.File.Create(filePath)) + { + await file.CopyToAsync(fs); + fs.Flush(); + } + + return bucketBindDomain + fileUrl; + } + #endregion + + #region 阿里云上传方法(File) + /// + /// 阿里云上传方法(File) + /// + /// + /// + /// + /// + public async Task UpLoadFileForAliYunOSS(FilesStorageOptions options, string fileExt, IFormFile file) + { + var jm = new AdminUiCallBack(); + + var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; + var today = DateTime.Now.ToString("yyyyMMdd"); + + //上传到阿里云 + await using var fileStream = file.OpenReadStream(); + var md5 = OssUtils.ComputeContentMd5(fileStream, file.Length); + + var filePath = options.Path + today + "/" + newFileName; //云文件保存路径 + //初始化阿里云配置--外网Endpoint、访问ID、访问password + var aliYun = new OssClient(options.Endpoint, options.AccessKeyId, options.AccessKeySecret); + //将文件md5值赋值给meat头信息,服务器验证文件MD5 + var objectMeta = new ObjectMetadata + { + ContentMd5 = md5 + }; + //文件上传--空间名、文件保存路径、文件流、meta头信息(文件md5) //返回meta头信息(文件md5) + aliYun.PutObject(options.BucketName, filePath, fileStream, objectMeta); + //返回给UEditor的插入编辑器的图片的src + + return options.BucketBindUrl + filePath; + } + + #endregion + + #region 腾讯云存储上传方法(File) + /// + /// 腾讯云存储上传方法(File) + /// + /// + /// + /// + /// + public async Task UpLoadFileForQCloudOSS(FilesStorageOptions options, string fileExt, IFormFile file) + { + var jm = new AdminUiCallBack(); + + var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; + var today = DateTime.Now.ToString("yyyyMMdd"); + + var filePath = options.Path + today + "/" + newFileName; //云文件保存路径 + + //上传到腾讯云OSS + //初始化 CosXmlConfig + string appid = options.AccountId;//设置腾讯云账户的账户标识 APPID + string region = options.CosRegion; //设置一个默认的存储桶地域 + CosXmlConfig config = new CosXmlConfig.Builder() + //.SetAppid(appid) + .IsHttps(true) //设置默认 HTTPS 请求 + .SetRegion(region) //设置一个默认的存储桶地域 + .SetDebugLog(true) //显示日志 + .Build(); //创建 CosXmlConfig 对象 + + long durationSecond = 600; //每次请求签名有效时长,单位为秒 + QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(options.AccessKeyId, options.AccessKeySecret, durationSecond); + + + byte[] bytes; + await using (var ms = new MemoryStream()) + { + await file.CopyToAsync(ms); + bytes = ms.ToArray(); + } + + var cosXml = new CosXmlServer(config, qCloudCredentialProvider); + COSXML.Model.Object.PutObjectRequest putObjectRequest = new COSXML.Model.Object.PutObjectRequest(options.TencentBucketName, filePath, bytes); + cosXml.PutObject(putObjectRequest); + + return options.BucketBindUrl + filePath; + } + #endregion + + #region 七牛云存储上传(File) + /// + /// 七牛云存储上传(File) + /// + /// + /// + /// + /// + public async Task UpLoadFileForQiNiuKoDo(FilesStorageOptions options, string fileExt, IFormFile file) + { + var jm = new AdminUiCallBack(); + + var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_fffff", DateTimeFormatInfo.InvariantInfo) + fileExt; + + Mac mac = new Mac(options.AccessKeyId, options.AccessKeySecret); + + byte[] bytes; + await using (var ms = new MemoryStream()) + { + await file.CopyToAsync(ms); + bytes = ms.ToArray(); + } + + // 设置上传策略 + PutPolicy putPolicy = new PutPolicy(); + // 设置要上传的目标空间 + putPolicy.Scope = options.QiNiuBucketName; + // 上传策略的过期时间(单位:秒) + putPolicy.SetExpires(3600); + // 文件上传完毕后,在多少天后自动被删除 + putPolicy.DeleteAfterDays = 1; + // 生成上传token + string token = Qiniu.Util.Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); + + Config config = new Config(); + // 设置 http 或者 https 上传 + config.UseHttps = true; + config.UseCdnDomains = true; + config.ChunkSize = ChunkUnit.U512K; + + UploadManager um = new UploadManager(config); + var outData = um.UploadData(bytes, newFileName, token, null); + + return options.BucketBindUrl + newFileName; + } + #endregion + + + #region 本地上传方法(Base64) + /// + /// 本地上传方法(Base64) + /// + /// + /// + /// + public string UpLoadBase64ForLocalStorage(FilesStorageOptions options, MemoryStream memStream) + { + var jm = new AdminUiCallBack(); + + var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + ".jpg"; + var today = DateTime.Now.ToString("yyyyMMdd"); + + Image mImage = Image.FromStream(memStream); + Bitmap bp = new Bitmap(mImage); + + var saveUrl = options.Path + today + "/"; + var dirPath = _webHostEnvironment.WebRootPath + saveUrl; + string bucketBindDomain = AppSettingsConstVars.AppConfigAppUrl; + + if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); + var filePath = dirPath + newFileName; + var fileUrl = saveUrl + newFileName; + + bp.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);//注意保存路径 + + return bucketBindDomain + fileUrl; + } + #endregion + + #region 阿里云上传方法(Base64) + /// + /// 阿里云上传方法(Base64) + /// + /// + /// + /// + public async Task UpLoadBase64ForAliYunOSS(FilesStorageOptions options, MemoryStream memStream) + { + var jm = new AdminUiCallBack(); + + var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + ".jpg"; + var today = DateTime.Now.ToString("yyyyMMdd"); + + // 设置当前流的位置为流的开始 + memStream.Seek(0, SeekOrigin.Begin); + + await using var fileStream = memStream; + var md5 = OssUtils.ComputeContentMd5(fileStream, memStream.Length); + + var filePath = options.Path + today + "/" + newFileName; //云文件保存路径 + //初始化阿里云配置--外网Endpoint、访问ID、访问password + var aliyun = new OssClient(options.Endpoint, options.AccessKeyId, options.AccessKeySecret); + //将文件md5值赋值给meat头信息,服务器验证文件MD5 + var objectMeta = new ObjectMetadata + { + ContentMd5 = md5 + }; + //文件上传--空间名、文件保存路径、文件流、meta头信息(文件md5) //返回meta头信息(文件md5) + aliyun.PutObject(options.BucketName, filePath, fileStream, objectMeta); + //返回给UEditor的插入编辑器的图片的src + + return options.BucketBindUrl + filePath; + + } + + #endregion + + #region 腾讯云存储上传方法(Base64) + + /// + /// 腾讯云存储上传方法(Base64) + /// + /// + /// + /// + public string UpLoadBase64ForQCloudOSS(FilesStorageOptions options, byte[] bytes) + { + var jm = new AdminUiCallBack(); + + var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + ".jpg"; + var today = DateTime.Now.ToString("yyyyMMdd"); + + //初始化 CosXmlConfig + string appid = options.AccountId;//设置腾讯云账户的账户标识 APPID + string region = options.CosRegion; //设置一个默认的存储桶地域 + CosXmlConfig config = new CosXmlConfig.Builder() + //.SetAppid(appid) + .IsHttps(true) //设置默认 HTTPS 请求 + .SetRegion(region) //设置一个默认的存储桶地域 + .SetDebugLog(true) //显示日志 + .Build(); //创建 CosXmlConfig 对象 + + long durationSecond = 600; //每次请求签名有效时长,单位为秒 + QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(options.AccessKeyId, options.AccessKeySecret, durationSecond); + + var cosXml = new CosXmlServer(config, qCloudCredentialProvider); + + var filePath = options.Path + today + "/" + newFileName; //云文件保存路径 + COSXML.Model.Object.PutObjectRequest putObjectRequest = new COSXML.Model.Object.PutObjectRequest(options.TencentBucketName, filePath, bytes); + + cosXml.PutObject(putObjectRequest); + + return options.BucketBindUrl + filePath; + } + #endregion + + #region 牛云上传方法(Base64) + + /// + /// 七牛云上传方法(Base64) + /// + /// + /// + /// + public string UpLoadBase64ForQiNiuKoDo(FilesStorageOptions options, byte[] bytes) + { + var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_fffff", DateTimeFormatInfo.InvariantInfo) + ".jpg"; + + Mac mac = new Mac(options.AccessKeyId, options.AccessKeySecret); + + // 设置上传策略 + PutPolicy putPolicy = new PutPolicy(); + // 设置要上传的目标空间 + putPolicy.Scope = options.QiNiuBucketName; + // 上传策略的过期时间(单位:秒) + putPolicy.SetExpires(3600); + // 文件上传完毕后,在多少天后自动被删除 + putPolicy.DeleteAfterDays = 1; + // 生成上传token + string token = Qiniu.Util.Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); + + Config config = new Config(); + // 设置 http 或者 https 上传 + config.UseHttps = true; + config.UseCdnDomains = true; + config.ChunkSize = ChunkUnit.U512K; + + UploadManager um = new UploadManager(config); + var outData = um.UploadData(bytes, newFileName, token, null); + + return options.BucketBindUrl + newFileName; + } + #endregion + + } } \ No newline at end of file diff --git a/CoreCms.Net.Services/CoreCms.Net.Services.csproj b/CoreCms.Net.Services/CoreCms.Net.Services.csproj index 53bb1847322e8727ab692a279fe2bbd4e7bf2a3e..60d9e97ff776352189ea2f67d52a98b0421ef7a7 100644 --- a/CoreCms.Net.Services/CoreCms.Net.Services.csproj +++ b/CoreCms.Net.Services/CoreCms.Net.Services.csproj @@ -5,13 +5,16 @@ + + + diff --git a/CoreCms.Net.Services/Shop/CoreCmsSettingServices.cs b/CoreCms.Net.Services/Shop/CoreCmsSettingServices.cs index d78746942529c6006c6787d711d164f36c976067..9280b4f5325d874c7d0bf93139642304a6f24d10 100644 --- a/CoreCms.Net.Services/Shop/CoreCmsSettingServices.cs +++ b/CoreCms.Net.Services/Shop/CoreCmsSettingServices.cs @@ -191,6 +191,9 @@ namespace CoreCms.Net.Services filesStorageOptions.BucketName = GetValue(SystemSettingConstVars.FilesStorageAliYunBucketName, configs, settings); filesStorageOptions.Endpoint = GetValue(SystemSettingConstVars.FilesStorageAliYunEndpoint, configs, settings); + //七牛云 + filesStorageOptions.QiNiuBucketName = GetValue(SystemSettingConstVars.FilesStorageQiNiuBucketName, configs, settings); + //格式化存储文件夹路径 filesStorageOptions.Path = UpLoadHelper.PathFormat(filesStorageOptions.StorageType, filesStorageOptions.Path); diff --git a/CoreCms.Net.Uni-App/CoreShop/components/coreshop-page/coreshop-goodTabBar.vue b/CoreCms.Net.Uni-App/CoreShop/components/coreshop-page/coreshop-goodTabBar.vue index f82c9908744b72e06e5188b270a22111f55a55d4..c8de91557ccb38987785fa5f6ac449c1f08e049f 100644 --- a/CoreCms.Net.Uni-App/CoreShop/components/coreshop-page/coreshop-goodTabBar.vue +++ b/CoreCms.Net.Uni-App/CoreShop/components/coreshop-page/coreshop-goodTabBar.vue @@ -113,6 +113,7 @@ mounted() { this.newData = this.coreshopdata; for (var i = 0; i < this.newData.parameters.list.length; i++) { + this.newData.parameters.list[i].isShow = i == 0; let item = { name: this.newData.parameters.list[i].title } diff --git a/CoreCms.Net.Web.Admin/Controllers/Com/ToolsController.cs b/CoreCms.Net.Web.Admin/Controllers/Com/ToolsController.cs index 732c11d1f350308b0d837002bd6f5ff40031ac21..757f03ad859caeac39f9e9de2916aaf6f7af33b9 100644 --- a/CoreCms.Net.Web.Admin/Controllers/Com/ToolsController.cs +++ b/CoreCms.Net.Web.Admin/Controllers/Com/ToolsController.cs @@ -85,6 +85,8 @@ namespace CoreCms.Net.Web.Admin.Controllers private readonly ICoreCmsProductsServices _productsServices; private readonly ICoreCmsServicesServices _servicesServices; private readonly ICoreCmsPagesServices _pagesServices; + private readonly IToolsServices _toolsServices; + private readonly WeChat.Service.HttpClients.IWeChatApiHttpClientFactory _weChatApiHttpClientFactory; @@ -111,7 +113,7 @@ namespace CoreCms.Net.Web.Admin.Controllers , ISysMenuServices sysMenuServices , ISysUserRoleServices sysUserRoleServices , ISysOrganizationServices sysOrganizationServices, ICodeGeneratorServices codeGeneratorServices, - ICoreCmsLogisticsServices logisticsServices, ISysLoginRecordServices sysLoginRecordServices, ISysNLogRecordsServices sysNLogRecordsServices, ICoreCmsBillPaymentsServices paymentsServices, ICoreCmsBillDeliveryServices billDeliveryServices, ICoreCmsUserServices userServices, ICoreCmsOrderServices orderServices, ICoreCmsBillAftersalesServices aftersalesServices, ICoreCmsSettingServices settingServices, ICoreCmsProductsServices productsServices, ICoreCmsServicesServices servicesServices, IOptions filesStorageOptions, ISysRoleMenuServices sysRoleMenuServices, IWeChatApiHttpClientFactory weChatApiHttpClientFactory, ICoreCmsPagesServices pagesServices) + ICoreCmsLogisticsServices logisticsServices, ISysLoginRecordServices sysLoginRecordServices, ISysNLogRecordsServices sysNLogRecordsServices, ICoreCmsBillPaymentsServices paymentsServices, ICoreCmsBillDeliveryServices billDeliveryServices, ICoreCmsUserServices userServices, ICoreCmsOrderServices orderServices, ICoreCmsBillAftersalesServices aftersalesServices, ICoreCmsSettingServices settingServices, ICoreCmsProductsServices productsServices, ICoreCmsServicesServices servicesServices, IOptions filesStorageOptions, ISysRoleMenuServices sysRoleMenuServices, IWeChatApiHttpClientFactory weChatApiHttpClientFactory, ICoreCmsPagesServices pagesServices, IToolsServices toolsServices) { _user = user; _webHostEnvironment = webHostEnvironment; @@ -145,6 +147,7 @@ namespace CoreCms.Net.Web.Admin.Controllers _sysRoleMenuServices = sysRoleMenuServices; _weChatApiHttpClientFactory = weChatApiHttpClientFactory; _pagesServices = pagesServices; + _toolsServices = toolsServices; } #region 获取登录用户用户信息(用于面板展示)==================================================== @@ -367,10 +370,10 @@ namespace CoreCms.Net.Web.Admin.Controllers { var jm = new AdminUiCallBack(); - var _filesStorageOptions = await _coreCmsSettingServices.GetFilesStorageOptions(); + var filesStorageOptions = await _coreCmsSettingServices.GetFilesStorageOptions(); //初始化上传参数 - var maxSize = 1024 * 1024 * _filesStorageOptions.MaxSize; //上传大小5M + var maxSize = 1024 * 1024 * filesStorageOptions.MaxSize; //上传大小5M var file = Request.Form.Files["file"]; if (file == null) @@ -385,112 +388,44 @@ namespace CoreCms.Net.Web.Admin.Controllers //检查大小 if (file.Length > maxSize) { - jm.msg = "上传文件大小超过限制,最大允许上传" + _filesStorageOptions.MaxSize + "M"; + jm.msg = "上传文件大小超过限制,最大允许上传" + filesStorageOptions.MaxSize + "M"; return jm; } //检查文件扩展名 - if (string.IsNullOrEmpty(fileExt) || - Array.IndexOf(_filesStorageOptions.FileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) + if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(filesStorageOptions.FileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) { - jm.msg = "上传文件扩展名是不允许的扩展名,请上传后缀名为:" + _filesStorageOptions.FileTypes; + jm.msg = "上传文件扩展名是不允许的扩展名,请上传后缀名为:" + filesStorageOptions.FileTypes; return jm; } - var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; - var today = DateTime.Now.ToString("yyyyMMdd"); - - if (_filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.LocalStorage.ToString()) + string url = string.Empty; + if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.LocalStorage.ToString()) { - var saveUrl = _filesStorageOptions.Path + today + "/"; - var dirPath = _webHostEnvironment.WebRootPath + saveUrl; - if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); - var filePath = dirPath + newFileName; - var fileUrl = saveUrl + newFileName; - - string bucketBindDomain = AppSettingsConstVars.AppConfigAppUrl; - - await using (var fs = System.IO.File.Create(filePath)) - { - await file.CopyToAsync(fs); - fs.Flush(); - } - - jm.code = 0; - jm.msg = "上传成功!"; - jm.data = new - { - fileUrl = bucketBindDomain + fileUrl, - src = bucketBindDomain + fileUrl - }; + url = await _toolsServices.UpLoadFileForLocalStorage(filesStorageOptions, fileExt, file); } - else if (_filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.AliYunOSS.ToString()) + else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.AliYunOSS.ToString()) { - - //上传到阿里云 - await using (var fileStream = file.OpenReadStream()) //转成Stream流 - { - var md5 = OssUtils.ComputeContentMd5(fileStream, file.Length); - - var filePath = _filesStorageOptions.Path + today + "/" + newFileName; //云文件保存路径 - //初始化阿里云配置--外网Endpoint、访问ID、访问password - var aliyun = new OssClient(_filesStorageOptions.Endpoint, _filesStorageOptions.AccessKeyId, _filesStorageOptions.AccessKeySecret); - //将文件md5值赋值给meat头信息,服务器验证文件MD5 - var objectMeta = new ObjectMetadata - { - ContentMd5 = md5 - }; - //文件上传--空间名、文件保存路径、文件流、meta头信息(文件md5) //返回meta头信息(文件md5) - aliyun.PutObject(_filesStorageOptions.BucketName, filePath, fileStream, objectMeta); - //返回给UEditor的插入编辑器的图片的src - jm.code = 0; - jm.msg = "上传成功"; - jm.data = new - { - fileUrl = _filesStorageOptions.BucketBindUrl + filePath, - src = _filesStorageOptions.BucketBindUrl + filePath - }; - } + url = await _toolsServices.UpLoadFileForAliYunOSS(filesStorageOptions, fileExt, file); } - else if (_filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.QCloudOSS.ToString()) + else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.QCloudOSS.ToString()) { - var filePath = _filesStorageOptions.Path + today + "/" + newFileName; //云文件保存路径 - - //上传到腾讯云OSS - //初始化 CosXmlConfig - string appid = _filesStorageOptions.AccountId;//设置腾讯云账户的账户标识 APPID - string region = _filesStorageOptions.CosRegion; //设置一个默认的存储桶地域 - CosXmlConfig config = new CosXmlConfig.Builder() - //.SetAppid(appid) - .IsHttps(true) //设置默认 HTTPS 请求 - .SetRegion(region) //设置一个默认的存储桶地域 - .SetDebugLog(true) //显示日志 - .Build(); //创建 CosXmlConfig 对象 - - long durationSecond = 600; //每次请求签名有效时长,单位为秒 - QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(_filesStorageOptions.AccessKeyId, _filesStorageOptions.AccessKeySecret, durationSecond); - - - byte[] bytes; - await using (var ms = new MemoryStream()) - { - await file.CopyToAsync(ms); - bytes = ms.ToArray(); - } - - var cosXml = new CosXmlServer(config, qCloudCredentialProvider); - COSXML.Model.Object.PutObjectRequest putObjectRequest = new COSXML.Model.Object.PutObjectRequest(_filesStorageOptions.TencentBucketName, filePath, bytes); - cosXml.PutObject(putObjectRequest); + url = await _toolsServices.UpLoadFileForQCloudOSS(filesStorageOptions, fileExt, file); + } + else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.QiNiuKoDo.ToString()) + { + url = await _toolsServices.UpLoadFileForQiNiuKoDo(filesStorageOptions, fileExt, file); + } - jm.code = 0; - jm.msg = "上传成功"; - jm.data = new - { - fileUrl = _filesStorageOptions.BucketBindUrl + filePath, - src = _filesStorageOptions.BucketBindUrl + filePath - }; + var bl = !string.IsNullOrEmpty(url); + jm.code = bl ? 0 : 1; + jm.msg = bl ? "上传成功!" : "上传失败"; + jm.data = new + { + fileUrl = url, + src = url + }; - } return jm; } @@ -507,9 +442,7 @@ namespace CoreCms.Net.Web.Admin.Controllers { var jm = new AdminUiCallBack(); - var _filesStorageOptions = await _coreCmsSettingServices.GetFilesStorageOptions(); - - + var filesStorageOptions = await _coreCmsSettingServices.GetFilesStorageOptions(); if (string.IsNullOrEmpty(entity.base64)) { @@ -521,104 +454,35 @@ namespace CoreCms.Net.Web.Admin.Controllers byte[] bytes = Convert.FromBase64String(entity.base64); MemoryStream memStream = new MemoryStream(bytes); - Image mImage = Image.FromStream(memStream); - Bitmap bp = new Bitmap(mImage); - - - var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + ".jpg"; - var today = DateTime.Now.ToString("yyyyMMdd"); - - - if (_filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.LocalStorage.ToString()) + string url = string.Empty; + if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.LocalStorage.ToString()) { - var saveUrl = _filesStorageOptions.Path + today + "/"; - var dirPath = _webHostEnvironment.WebRootPath + saveUrl; - string bucketBindDomain = AppSettingsConstVars.AppConfigAppUrl; - - if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); - var filePath = dirPath + newFileName; - var fileUrl = saveUrl + newFileName; - - bp.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);//注意保存路径 - - jm.code = 0; - jm.msg = "上传成功!"; - jm.data = new - { - fileUrl = bucketBindDomain + fileUrl, - src = bucketBindDomain + fileUrl - }; - jm.otherData = GlobalEnumVars.FilesStorageOptionsType.LocalStorage.ToString(); - + url = _toolsServices.UpLoadBase64ForLocalStorage(filesStorageOptions, memStream); } - else if (_filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.AliYunOSS.ToString()) + else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.AliYunOSS.ToString()) { //上传到阿里云 - - // 设置当前流的位置为流的开始 - memStream.Seek(0, SeekOrigin.Begin); - - await using (var fileStream = memStream) //转成Stream流 - { - var md5 = OssUtils.ComputeContentMd5(fileStream, memStream.Length); - - var filePath = _filesStorageOptions.Path + today + "/" + newFileName; //云文件保存路径 - //初始化阿里云配置--外网Endpoint、访问ID、访问password - var aliyun = new OssClient(_filesStorageOptions.Endpoint, _filesStorageOptions.AccessKeyId, _filesStorageOptions.AccessKeySecret); - //将文件md5值赋值给meat头信息,服务器验证文件MD5 - var objectMeta = new ObjectMetadata - { - ContentMd5 = md5 - }; - //文件上传--空间名、文件保存路径、文件流、meta头信息(文件md5) //返回meta头信息(文件md5) - aliyun.PutObject(_filesStorageOptions.BucketName, filePath, fileStream, objectMeta); - //返回给UEditor的插入编辑器的图片的src - jm.code = 0; - jm.msg = "上传成功"; - jm.data = new - { - fileUrl = _filesStorageOptions.BucketBindUrl + filePath, - src = _filesStorageOptions.BucketBindUrl + filePath - }; - } - jm.otherData = GlobalEnumVars.FilesStorageOptionsType.AliYunOSS.ToString(); + url = await _toolsServices.UpLoadBase64ForAliYunOSS(filesStorageOptions, memStream); } - else if (_filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.QCloudOSS.ToString()) + else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.QCloudOSS.ToString()) { //上传到腾讯云OSS - //初始化 CosXmlConfig - string appid = _filesStorageOptions.AccountId;//设置腾讯云账户的账户标识 APPID - string region = _filesStorageOptions.CosRegion; //设置一个默认的存储桶地域 - CosXmlConfig config = new CosXmlConfig.Builder() - //.SetAppid(appid) - .IsHttps(true) //设置默认 HTTPS 请求 - .SetRegion(region) //设置一个默认的存储桶地域 - .SetDebugLog(true) //显示日志 - .Build(); //创建 CosXmlConfig 对象 - - long durationSecond = 600; //每次请求签名有效时长,单位为秒 - QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider( - _filesStorageOptions.AccessKeyId, _filesStorageOptions.AccessKeySecret, durationSecond); - - - var cosXml = new CosXmlServer(config, qCloudCredentialProvider); - - var filePath = _filesStorageOptions.Path + today + "/" + newFileName; //云文件保存路径 - COSXML.Model.Object.PutObjectRequest putObjectRequest = new COSXML.Model.Object.PutObjectRequest(_filesStorageOptions.TencentBucketName, filePath, bytes); - - cosXml.PutObject(putObjectRequest); - - jm.code = 0; - jm.msg = "上传成功"; - jm.data = new - { - fileUrl = _filesStorageOptions.BucketBindUrl + filePath, - src = _filesStorageOptions.BucketBindUrl + filePath - }; + url = _toolsServices.UpLoadBase64ForQCloudOSS(filesStorageOptions, bytes); } - jm.otherData = _filesStorageOptions; - + else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.QiNiuKoDo.ToString()) + { + //上传到七牛云kodo + url = _toolsServices.UpLoadBase64ForQiNiuKoDo(filesStorageOptions, bytes); + } + var bl = !string.IsNullOrEmpty(url); + jm.code = bl ? 0 : 1; + jm.msg = bl ? "上传成功!" : "上传失败"; + jm.data = new + { + fileUrl = url, + src = url + }; return jm; } @@ -636,10 +500,10 @@ namespace CoreCms.Net.Web.Admin.Controllers { var jm = new CKEditorUploadedResult(); - var _filesStorageOptions = await _coreCmsSettingServices.GetFilesStorageOptions(); + var filesStorageOptions = await _coreCmsSettingServices.GetFilesStorageOptions(); //初始化上传参数 - var maxSize = 1024 * 1024 * _filesStorageOptions.MaxSize; //上传大小5M + var maxSize = 1024 * 1024 * filesStorageOptions.MaxSize; //上传大小5M var file = Request.Form.Files["upload"]; if (file == null) @@ -654,103 +518,38 @@ namespace CoreCms.Net.Web.Admin.Controllers //检查大小 if (file.Length > maxSize) { - jm.error.message = "上传文件大小超过限制,最大允许上传" + _filesStorageOptions.MaxSize + "M"; + jm.error.message = "上传文件大小超过限制,最大允许上传" + filesStorageOptions.MaxSize + "M"; return jm; } //检查文件扩展名 - if (string.IsNullOrEmpty(fileExt) || - Array.IndexOf(_filesStorageOptions.FileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) + if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(filesStorageOptions.FileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) { - jm.error.message = "上传文件扩展名是不允许的扩展名,请上传后缀名为:" + _filesStorageOptions.FileTypes; + jm.error.message = "上传文件扩展名是不允许的扩展名,请上传后缀名为:" + filesStorageOptions.FileTypes; return jm; } - var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; - var today = DateTime.Now.ToString("yyyyMMdd"); - - - if (_filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.LocalStorage.ToString()) + string url = string.Empty; + if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.LocalStorage.ToString()) { - var saveUrl = _filesStorageOptions.Path + today + "/"; - var dirPath = _webHostEnvironment.WebRootPath + saveUrl; - if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); - var filePath = dirPath + newFileName; - var fileUrl = saveUrl + newFileName; - - string bucketBindDomain = AppSettingsConstVars.AppConfigAppUrl; - - await using (var fs = System.IO.File.Create(filePath)) - { - await file.CopyToAsync(fs); - fs.Flush(); - } - - jm.uploaded = 1; - jm.fileName = fileName; - jm.url = bucketBindDomain + fileUrl; + url = await _toolsServices.UpLoadFileForLocalStorage(filesStorageOptions, fileExt, file); } - else if (_filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.AliYunOSS.ToString()) + else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.AliYunOSS.ToString()) { //上传到阿里云 - await using (var fileStream = file.OpenReadStream()) //转成Stream流 - { - var md5 = OssUtils.ComputeContentMd5(fileStream, file.Length); - - var filePath = _filesStorageOptions.Path + today + "/" + newFileName; //云文件保存路径 - //初始化阿里云配置--外网Endpoint、访问ID、访问password - var aliyun = new OssClient(_filesStorageOptions.Endpoint, _filesStorageOptions.AccessKeyId, _filesStorageOptions.AccessKeySecret); - //将文件md5值赋值给meat头信息,服务器验证文件MD5 - var objectMeta = new ObjectMetadata - { - ContentMd5 = md5 - }; - //文件上传--空间名、文件保存路径、文件流、meta头信息(文件md5) //返回meta头信息(文件md5) - aliyun.PutObject(_filesStorageOptions.BucketName, filePath, fileStream, objectMeta); - //返回给UEditor的插入编辑器的图片的src - - jm.uploaded = 1; - jm.fileName = fileName; - jm.url = _filesStorageOptions.BucketBindUrl + filePath; - - } + url = await _toolsServices.UpLoadFileForAliYunOSS(filesStorageOptions, fileExt, file); } - else if (_filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.QCloudOSS.ToString()) + else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.QCloudOSS.ToString()) { - var filePath = _filesStorageOptions.Path + today + "/" + newFileName; //云文件保存路径 - - //上传到腾讯云OSS - //初始化 CosXmlConfig - string appid = _filesStorageOptions.AccountId;//设置腾讯云账户的账户标识 APPID - string region = _filesStorageOptions.CosRegion; //设置一个默认的存储桶地域 - CosXmlConfig config = new CosXmlConfig.Builder() - //.SetAppid(appid) - .IsHttps(true) //设置默认 HTTPS 请求 - .SetRegion(region) //设置一个默认的存储桶地域 - .SetDebugLog(true) //显示日志 - .Build(); //创建 CosXmlConfig 对象 - - long durationSecond = 600; //每次请求签名有效时长,单位为秒 - QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(_filesStorageOptions.AccessKeyId, _filesStorageOptions.AccessKeySecret, durationSecond); - - - byte[] bytes; - await using (var ms = new MemoryStream()) - { - await file.CopyToAsync(ms); - bytes = ms.ToArray(); - } - - var cosXml = new CosXmlServer(config, qCloudCredentialProvider); - COSXML.Model.Object.PutObjectRequest putObjectRequest = new COSXML.Model.Object.PutObjectRequest(_filesStorageOptions.TencentBucketName, filePath, bytes); - cosXml.PutObject(putObjectRequest); - - jm.uploaded = 1; - jm.fileName = fileName; - jm.url = _filesStorageOptions.BucketBindUrl + filePath; - + url = await _toolsServices.UpLoadFileForQCloudOSS(filesStorageOptions, fileExt, file); } - + else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.QiNiuKoDo.ToString()) + { + url = await _toolsServices.UpLoadFileForQiNiuKoDo(filesStorageOptions, fileExt, file); + } + jm.uploaded = !string.IsNullOrEmpty(url) ? 1 : 0; + jm.fileName = fileName; + jm.url = url; return jm; } diff --git a/CoreCms.Net.Web.Admin/appsettings.json b/CoreCms.Net.Web.Admin/appsettings.json index 440779ec682ac0f1a1f4eb8c1699e821dd540f9b..0528d124d6e38adde90ff9d95d0adb74bc73b525 100644 --- a/CoreCms.Net.Web.Admin/appsettings.json +++ b/CoreCms.Net.Web.Admin/appsettings.json @@ -1,7 +1,7 @@ { "ConnectionStrings": { "DbType": "SqlServer", //数据库将支持两种模式【SqlServer,MySql】 - "SqlConnection": "Server=127.0.0.1;uid=CoreShop;pwd=CoreShop;Database=CoreShop;MultipleActiveResultSets=true;pooling=true;min pool size=5;max pool size=32767;connect timeout=20;" + "SqlConnection": "Server=127.0.0.1;uid=CoreShop;pwd=CoreShop;Database=CoreShop;MultipleActiveResultSets=true;pooling=true;min pool size=5;max pool size=32767;connect timeout=20;Encrypt=True;TrustServerCertificate=True;" //SqlServer数据库连接字符串,需要开启数据库连接复用【MultipleActiveResultSets=true】 // 如果采用容器化部署Service 要写成mysql的服务名,否则写地址 diff --git a/CoreCms.Net.Web.Admin/wwwroot/views/shop/setting/index.html b/CoreCms.Net.Web.Admin/wwwroot/views/shop/setting/index.html index 0e659f56632cd460c34aa208ba188837ec9046f6..077ac703f5add59222cf1e139e0c95c6cb8b7ebc 100644 --- a/CoreCms.Net.Web.Admin/wwwroot/views/shop/setting/index.html +++ b/CoreCms.Net.Web.Admin/wwwroot/views/shop/setting/index.html @@ -548,7 +548,7 @@
-
请使用路径,如"/upload/doc/",路径前后都要加“/”
+
请使用路径,如"/upload/doc/",路径前后都要加“/”(七牛云为key/value结构不支持)
@@ -621,7 +621,14 @@
- +
+
+ +
+ +
+
+
@@ -909,14 +916,22 @@ $("#cloudConfig").hide(); $("#tencentCloud").hide(); $("#aliyun").hide(); + $("#qiniu").hide(); } else if (data.value == 'AliYunOSS') { $("#cloudConfig").show(); $("#tencentCloud").hide(); $("#aliyun").show(); + $("#qiniu").hide(); } else if (data.value == 'QCloudOSS') { $("#cloudConfig").show(); $("#tencentCloud").show(); $("#aliyun").hide(); + $("#qiniu").hide(); + } else if (data.value == 'QiNiuKoDo') { + $("#cloudConfig").show(); + $("#tencentCloud").hide(); + $("#aliyun").hide(); + $("#qiniu").show(); } }); @@ -928,14 +943,22 @@ $("#cloudConfig").hide(); $("#tencentCloud").hide(); $("#aliyun").hide(); + $("#qiniu").hide(); } else if (obj.sValue == 'AliYunOSS') { $("#cloudConfig").show(); $("#tencentCloud").hide(); $("#aliyun").show(); + $("#qiniu").hide(); } else if (obj.sValue == 'QCloudOSS') { $("#cloudConfig").show(); $("#tencentCloud").show(); $("#aliyun").hide(); + $("#qiniu").hide(); + } else if (obj.sValue == 'QiNiuKoDo') { + $("#cloudConfig").show(); + $("#tencentCloud").hide(); + $("#aliyun").hide(); + $("#qiniu").show(); } } } diff --git a/CoreCms.Net.Web.WebApi/Controllers/CommonController.cs b/CoreCms.Net.Web.WebApi/Controllers/CommonController.cs index ccc3eaedbb610ab21086dca70af1bba9f376eb38..cdbb660d1117dd48aa07c137e48a71767ec3801b 100644 --- a/CoreCms.Net.Web.WebApi/Controllers/CommonController.cs +++ b/CoreCms.Net.Web.WebApi/Controllers/CommonController.cs @@ -48,6 +48,7 @@ namespace CoreCms.Net.Web.WebApi.Controllers private readonly ICoreCmsServiceDescriptionServices _serviceDescriptionServices; private readonly ICoreCmsSettingServices _coreCmsSettingServices; + private readonly IToolsServices _toolsServices; /// @@ -55,11 +56,12 @@ namespace CoreCms.Net.Web.WebApi.Controllers /// public CommonController(ICoreCmsSettingServices settingServices , ICoreCmsAreaServices areaServices - , IWebHostEnvironment webHostEnvironment, ICoreCmsServiceDescriptionServices serviceDescriptionServices, ICoreCmsSettingServices coreCmsSettingServices) + , IWebHostEnvironment webHostEnvironment, ICoreCmsServiceDescriptionServices serviceDescriptionServices, ICoreCmsSettingServices coreCmsSettingServices, IToolsServices toolsServices) { _webHostEnvironment = webHostEnvironment; _serviceDescriptionServices = serviceDescriptionServices; _coreCmsSettingServices = coreCmsSettingServices; + _toolsServices = toolsServices; _settingServices = settingServices; _areaServices = areaServices; @@ -260,10 +262,8 @@ namespace CoreCms.Net.Web.WebApi.Controllers { var jm = new WebApiCallBack(); - var filesStorageOptions = await _coreCmsSettingServices.GetFilesStorageOptions(); - //初始化上传参数 var maxSize = 1024 * 1024 * filesStorageOptions.MaxSize; //上传大小5M @@ -291,110 +291,32 @@ namespace CoreCms.Net.Web.WebApi.Controllers return jm; } - string dts = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo); - string newFileName = dts + fileExt; - string today = DateTime.Now.ToString("yyyyMMdd"); - - - + string url = string.Empty; if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.LocalStorage.ToString()) { - string saveUrl = filesStorageOptions.Path + today + "/"; - string dirPath = _webHostEnvironment.WebRootPath + saveUrl; - if (!Directory.Exists(dirPath)) - { - Directory.CreateDirectory(dirPath); - } - string filePath = dirPath + newFileName; - string fileUrl = saveUrl + newFileName; - - string bucketBindDomain = AppSettingsConstVars.AppConfigAppInterFaceUrl; - - using (FileStream fs = System.IO.File.Create(filePath)) - { - file.CopyTo(fs); - fs.Flush(); - } - jm.status = true; - jm.msg = "上传成功!"; - jm.data = new - { - fileUrl = bucketBindDomain + fileUrl, - src = bucketBindDomain + fileUrl, - imageId = dts - }; - + url = await _toolsServices.UpLoadFileForLocalStorage(filesStorageOptions, fileExt, file); } else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.AliYunOSS.ToString()) { - //上传到阿里云 - using (Stream fileStream = file.OpenReadStream())//转成Stream流 - { - string md5 = OssUtils.ComputeContentMd5(fileStream, file.Length); - - string filePath = filesStorageOptions.Path + today + "/" + newFileName;//云文件保存路径 - //初始化阿里云配置--外网Endpoint、访问ID、访问password - var aliyun = new OssClient(filesStorageOptions.Endpoint, filesStorageOptions.AccessKeyId, filesStorageOptions.AccessKeySecret); - //将文件md5值赋值给meat头信息,服务器验证文件MD5 - var objectMeta = new ObjectMetadata - { - ContentMd5 = md5, - }; - //文件上传--空间名、文件保存路径、文件流、meta头信息(文件md5) //返回meta头信息(文件md5) - var outResult = aliyun.PutObject(filesStorageOptions.BucketName, filePath, fileStream, objectMeta); - //返回给UEditor的插入编辑器的图片的src - jm.status = true; - jm.msg = "上传成功"; - jm.data = new - { - fileUrl = filesStorageOptions.BucketBindUrl + filePath, - src = filesStorageOptions.BucketBindUrl + filePath, - imageId = dts - }; - return jm; - } + url = await _toolsServices.UpLoadFileForAliYunOSS(filesStorageOptions, fileExt, file); } else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.QCloudOSS.ToString()) { - var filePath = filesStorageOptions.Path + today + "/" + newFileName; //云文件保存路径 - - //上传到腾讯云OSS - //初始化 CosXmlConfig - string appid = filesStorageOptions.AccountId;//设置腾讯云账户的账户标识 APPID - string region = filesStorageOptions.CosRegion; //设置一个默认的存储桶地域 - CosXmlConfig config = new CosXmlConfig.Builder() - //.SetAppid(appid) - .IsHttps(true) //设置默认 HTTPS 请求 - .SetRegion(region) //设置一个默认的存储桶地域 - .SetDebugLog(true) //显示日志 - .Build(); //创建 CosXmlConfig 对象 - - long durationSecond = 600; //每次请求签名有效时长,单位为秒 - QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(filesStorageOptions.AccessKeyId, filesStorageOptions.AccessKeySecret, durationSecond); - - - byte[] bytes; - await using (var ms = new MemoryStream()) - { - await file.CopyToAsync(ms); - bytes = ms.ToArray(); - } - - var cosXml = new CosXmlServer(config, qCloudCredentialProvider); - COSXML.Model.Object.PutObjectRequest putObjectRequest = new COSXML.Model.Object.PutObjectRequest(filesStorageOptions.TencentBucketName, filePath, bytes); - cosXml.PutObject(putObjectRequest); - - jm.code = 0; - jm.msg = "上传成功"; - jm.data = new - { - fileUrl = filesStorageOptions.BucketBindUrl + filePath, - src = filesStorageOptions.BucketBindUrl + filePath, - imageId = dts - }; - + url = await _toolsServices.UpLoadFileForQCloudOSS(filesStorageOptions, fileExt, file); + } + else if (filesStorageOptions.StorageType == GlobalEnumVars.FilesStorageOptionsType.QiNiuKoDo.ToString()) + { + url = await _toolsServices.UpLoadFileForQiNiuKoDo(filesStorageOptions, fileExt, file); } + var bl = !string.IsNullOrEmpty(url); + jm.code = bl ? 0 : 1; + jm.msg = bl ? "上传成功!" : "上传失败"; + jm.data = new + { + fileUrl = url, + src = url + }; return jm; } diff --git a/CoreCms.Net.Web.WebApi/Controllers/UserController.cs b/CoreCms.Net.Web.WebApi/Controllers/UserController.cs index 5ba43244719986da6ae2882dc4446c6ed3f7ae00..54594a740f565b86a547e3b6737508a0431fc777 100644 --- a/CoreCms.Net.Web.WebApi/Controllers/UserController.cs +++ b/CoreCms.Net.Web.WebApi/Controllers/UserController.cs @@ -11,9 +11,11 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; +using System.Threading; using System.Threading.Tasks; using CoreCms.Net.Auth.HttpContextUser; using CoreCms.Net.Auth.Policys; @@ -89,7 +91,6 @@ namespace CoreCms.Net.Web.WebApi.Controllers private readonly AsyncLock _mutex = new AsyncLock(); - /// /// 构造函数 /// @@ -176,61 +177,62 @@ namespace CoreCms.Net.Web.WebApi.Controllers var response = await client.ExecuteSnsJsCode2SessionAsync(request, HttpContext.RequestAborted); if (response.ErrorCode == (int)WeChatReturnCode.ReturnCode.请求成功) { - var userInfo = await _userWeChatInfoServices.QueryByClauseAsync(p => p.openid == response.OpenId); - if (userInfo == null) - { - userInfo = new CoreCmsUserWeChatInfo(); - userInfo.openid = response.OpenId; - userInfo.type = (int)GlobalEnumVars.UserAccountTypes.微信小程序; - userInfo.sessionKey = response.SessionKey; - userInfo.gender = 1; - userInfo.createTime = DateTime.Now; - - var id = await _userWeChatInfoServices.InsertAsync(userInfo); - } - else + using (await _mutex.LockAsync()) { - if (userInfo.sessionKey != response.SessionKey) + var userInfo = await _userWeChatInfoServices.QueryByClauseAsync(p => p.openid == response.OpenId); + if (userInfo == null) { - await _userWeChatInfoServices.UpdateAsync( - p => new CoreCmsUserWeChatInfo() { sessionKey = response.SessionKey, updateTime = DateTime.Now }, - p => p.openid == userInfo.openid); + userInfo = new CoreCmsUserWeChatInfo(); + userInfo.openid = response.OpenId; + userInfo.type = (int)GlobalEnumVars.UserAccountTypes.微信小程序; + userInfo.sessionKey = response.SessionKey; + userInfo.gender = 1; + userInfo.createTime = DateTime.Now; + + await _userWeChatInfoServices.InsertAsync(userInfo); } - } - - if (userInfo is { userId: > 0 }) - { - var user = await _userServices.QueryByClauseAsync(p => p.id == userInfo.userId); - if (user != null) + else { + if (userInfo.sessionKey != response.SessionKey) + { + await _userWeChatInfoServices.UpdateAsync( + p => new CoreCmsUserWeChatInfo() { sessionKey = response.SessionKey, updateTime = DateTime.Now }, + p => p.openid == userInfo.openid); + } + } - - var claims = new List { + if (userInfo is { userId: > 0 }) + { + var user = await _userServices.QueryByClauseAsync(p => p.id == userInfo.userId); + if (user != null) + { + var claims = new List { new Claim(ClaimTypes.Name, user.nickName), new Claim(JwtRegisteredClaimNames.Jti, user.id.ToString()), - new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString()) }; + new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString(CultureInfo.InvariantCulture)) }; - //用户标识 - var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); - identity.AddClaims(claims); - jm.status = true; - jm.data = new - { - auth = JwtToken.BuildJwtToken(claims.ToArray(), _permissionRequirement), - user - }; - jm.otherData = response.OpenId; - - //录入登录日志 - var log = new CoreCmsUserLog(); - log.userId = user.id; - log.state = (int)GlobalEnumVars.UserLogTypes.登录; - log.ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress != null ? _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() : "127.0.0.1"; - log.createTime = DateTime.Now; - log.parameters = GlobalEnumVars.UserLogTypes.登录.ToString(); - await _userLogServices.InsertAsync(log); - - return jm; + //用户标识 + var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); + identity.AddClaims(claims); + jm.status = true; + jm.data = new + { + auth = JwtToken.BuildJwtToken(claims.ToArray(), _permissionRequirement), + user + }; + jm.otherData = response.OpenId; + + //录入登录日志 + var log = new CoreCmsUserLog(); + log.userId = user.id; + log.state = (int)GlobalEnumVars.UserLogTypes.登录; + log.ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress != null ? _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() : "127.0.0.1"; + log.createTime = DateTime.Now; + log.parameters = GlobalEnumVars.UserLogTypes.登录.ToString(); + await _userLogServices.InsertAsync(log); + + return jm; + } } } @@ -267,8 +269,8 @@ namespace CoreCms.Net.Web.WebApi.Controllers { jm.status = false; jm.msg = "用户信息获取失败"; + return jm; } - var decodedEntity = EncryptHelper.DecodeUserInfoBySessionId(userInfo.sessionKey, entity.encryptedData, entity.iv); var token = string.Empty; var userWxId = entity.sessionAuthId; @@ -301,7 +303,7 @@ namespace CoreCms.Net.Web.WebApi.Controllers var claims = new List { new Claim(ClaimTypes.Name, user.nickName), new Claim(JwtRegisteredClaimNames.Jti, user.id.ToString()), - new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString()) }; + new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString(CultureInfo.InvariantCulture)) }; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); @@ -355,7 +357,7 @@ namespace CoreCms.Net.Web.WebApi.Controllers } if (entity.code == "login") { - var shave = _userServices.Exists(p => p.mobile == entity.mobile && p.userWx > 0); + var shave = await _userServices.ExistsAsync(p => p.mobile == entity.mobile && p.userWx > 0); if (shave) { jm.msg = "手机号码已被绑定,请更换"; @@ -399,6 +401,7 @@ namespace CoreCms.Net.Web.WebApi.Controllers { jm.status = false; jm.msg = "用户信息获取失败"; + return jm; } DecodedPhoneNumber phoneNumber; try @@ -420,7 +423,7 @@ namespace CoreCms.Net.Web.WebApi.Controllers sessionAuthId = entity.sessionAuthId }; - jm = await _userServices.SmsLogin(data, (int)GlobalEnumVars.LoginType.WeChatPhoneNumber, 1); + jm = await _userServices.SmsLogin(data); return jm; } @@ -511,7 +514,7 @@ namespace CoreCms.Net.Web.WebApi.Controllers var claims = new List { new Claim(ClaimTypes.Name, user.nickName), new Claim(JwtRegisteredClaimNames.Jti, id.ToString()), - new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString()) }; + new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString(CultureInfo.InvariantCulture)) }; //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); @@ -522,7 +525,7 @@ namespace CoreCms.Net.Web.WebApi.Controllers var log = new CoreCmsUserLog(); log.userId = id; log.state = (int)GlobalEnumVars.UserLogTypes.注册; - log.ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress != null ? + log.ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress != null ? _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() : "127.0.0.1"; log.createTime = DateTime.Now; log.parameters = GlobalEnumVars.UserLogTypes.注册.ToString(); @@ -588,7 +591,7 @@ namespace CoreCms.Net.Web.WebApi.Controllers var jm = new WebApiCallBack { status = true, msg = "获取成功" }; var allConfigs = await _settingServices.GetConfigDictionaries(); - jm.data = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.PointSwitch).ObjectToInt(2); ; + jm.data = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.PointSwitch).ObjectToInt(2); return jm; } @@ -938,20 +941,23 @@ namespace CoreCms.Net.Web.WebApi.Controllers var ship = await _userShipServices.QueryListByClauseAsync(p => p.userId == _user.ID, p => p.isDefault, OrderByType.Desc); if (ship.Any()) { - ship.ForEach(async p => - { - var fullName = await _areaServices.GetAreaFullName(p.areaId); - if (fullName.status) - { - p.areaName = fullName.data.ToString(); - } - }); + ship.ForEach(Action); } jm.status = true; jm.data = ship; return jm; } + + private async void Action(CoreCmsUserShip p) + { + var fullName = await _areaServices.GetAreaFullName(p.areaId); + if (fullName.status) + { + p.areaName = fullName.data.ToString(); + } + } + #endregion #region 保存用户地址 @@ -1157,10 +1163,8 @@ namespace CoreCms.Net.Web.WebApi.Controllers [Authorize] public async Task AddBankCards([FromBody] CoreCmsUserBankCard entity) { - var jm = new WebApiCallBack(); - entity.userId = _user.ID; - jm = await _userBankCardServices.AddBankCards(entity); + var jm = await _userBankCardServices.AddBankCards(entity); return jm; } @@ -1270,10 +1274,8 @@ namespace CoreCms.Net.Web.WebApi.Controllers [Authorize] public async Task Cash([FromBody] FMIntId entity) { - var jm = new WebApiCallBack(); - var money = entity.data.ObjectToDecimal(0); - jm = await _userTocashServices.Tocash(_user.ID, money, entity.id); + var jm = await _userTocashServices.Tocash(_user.ID, money, entity.id); return jm; } @@ -1288,11 +1290,8 @@ namespace CoreCms.Net.Web.WebApi.Controllers [Authorize] public async Task CashList([FromBody] FMPageByIntId entity) { - var jm = new WebApiCallBack(); - - jm = await _userTocashServices.UserToCashList(_user.ID, entity.page, entity.limit, entity.id); + var jm = await _userTocashServices.UserToCashList(_user.ID, entity.page, entity.limit, entity.id); return jm; - } #endregion @@ -1480,11 +1479,8 @@ namespace CoreCms.Net.Web.WebApi.Controllers [Authorize] public async Task GoodsCollection([FromBody] FMIntId entity) { - var jm = new WebApiCallBack(); - - jm = await _goodsCollectionServices.ToAdd(_user.ID, entity.id); + var jm = await _goodsCollectionServices.ToAdd(_user.ID, entity.id); return jm; - } #endregion @@ -1739,12 +1735,7 @@ namespace CoreCms.Net.Web.WebApi.Controllers [Authorize] public async Task GetMyInvite() { - var jm = await _userServices.GetMyInvite(_user.ID); - - var first = await _userServices.QueryChildCountAsync(_user.ID, 1); - var second = await _userServices.QueryChildCountAsync(_user.ID, 2); - - return jm; + return await _userServices.GetMyInvite(_user.ID); } #endregion @@ -1762,7 +1753,7 @@ namespace CoreCms.Net.Web.WebApi.Controllers { var jm = new WebApiCallBack(); - var first = await _userServices.QueryChildCountAsync(_user.ID, 1); + var first = await _userServices.QueryChildCountAsync(_user.ID); var second = await _userServices.QueryChildCountAsync(_user.ID, 2); var monthFirst = await _userServices.QueryChildCountAsync(_user.ID, 1, true); diff --git a/CoreCms.Net.Web.WebApi/appsettings.json b/CoreCms.Net.Web.WebApi/appsettings.json index 440779ec682ac0f1a1f4eb8c1699e821dd540f9b..0528d124d6e38adde90ff9d95d0adb74bc73b525 100644 --- a/CoreCms.Net.Web.WebApi/appsettings.json +++ b/CoreCms.Net.Web.WebApi/appsettings.json @@ -1,7 +1,7 @@ { "ConnectionStrings": { "DbType": "SqlServer", //数据库将支持两种模式【SqlServer,MySql】 - "SqlConnection": "Server=127.0.0.1;uid=CoreShop;pwd=CoreShop;Database=CoreShop;MultipleActiveResultSets=true;pooling=true;min pool size=5;max pool size=32767;connect timeout=20;" + "SqlConnection": "Server=127.0.0.1;uid=CoreShop;pwd=CoreShop;Database=CoreShop;MultipleActiveResultSets=true;pooling=true;min pool size=5;max pool size=32767;connect timeout=20;Encrypt=True;TrustServerCertificate=True;" //SqlServer数据库连接字符串,需要开启数据库连接复用【MultipleActiveResultSets=true】 // 如果采用容器化部署Service 要写成mysql的服务名,否则写地址