username@email.com
2024-08-22 17308f6494c81fb5a5ee035724a414ec7da11936
cylsg/EzUpFile/EzFileUploadService.cs
New file
@@ -0,0 +1,531 @@

using Aliyun.OSS;
using Aliyun.OSS.Util;
using cylsg.utility;
using cylsg.utility.Extend;
using EzTencentCloud;
using Furion;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System;
using System.Buffers.Text;
using System.Drawing;
using System.Globalization;
using System.Security.Policy;
using TencentCloud.Ocr.V20181119.Models;
using TencentCloud.Teo.V20220901.Models;
using Task = System.Threading.Tasks.Task;
namespace EzUpFile
{
    /// <summary>
    /// 附件服务程序
    /// </summary>
    public class EzFileUploadService : IEzFileUploadService, IScoped
    {
        private readonly HttpRequest? _request;
        private readonly ISqlSugarClient _sqlSugarClient;
        private readonly ITencentCloudService _tcs;
        public EzFileUploadService(IHttpContextAccessor httpContext, ISqlSugarClient sqlSugarClient,ITencentCloudService tencentCloudService)
        {
            _request = httpContext.HttpContext?.Request ?? null;
            _sqlSugarClient = sqlSugarClient;
            _tcs= tencentCloudService;
        }
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        public async Task<string> UploadFiles()
        {
            var maxSize = 1024 * 1024 * 5; //上传大小5M
            var file = _request?.Form?.Files["file"];
            if (file == null)
            {
                throw Oops.Oh("你没有选择文件");
            }
            var fileName = file.FileName;
            var fileExt = Path.GetExtension(fileName).ToLowerInvariant();
            //检查大小
            if (file.Length > maxSize)
            {
                throw Oops.Oh("文件大于设置文件");
            }
            ////检查文件扩展名
            //if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(op.AttachmentSaveFileExtName?.Split(',') ?? new string[] { "" }, fileExt.Substring(1).ToLower()) == -1)
            //{
            //    throw Oops.Oh("上传文件扩展名是不允许的扩展名,请上传后缀名为:" + op.AttachmentSaveFileExtName);
            //}
            string url = string.Empty;
            url = await UpLoadFileForAliYunOSS(fileExt, file);
            return url;
        }
        /// <summary>
        /// 上传base64
        /// </summary>
        /// <param name="base64"></param>
        /// <returns></returns>
        public async Task<string> UploadFilesFByBase64(string base64)
        {
            if (string.IsNullOrEmpty(base64))
            {
                throw Oops.Oh("没有内容");
            }
            //检查上传大小
            if (!CommonHelper.CheckBase64Size(base64, 5))
            {
                throw Oops.Oh("上传文件大小超过限制,最大允许上传" + "5" + "M");
            }
            base64 = base64.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
            byte[] bytes = Convert.FromBase64String(base64);
            MemoryStream memStream = new MemoryStream(bytes);
            string url = string.Empty;
            url = await UpLoadBase64ForAliYunOSS(memStream);
            return url;
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public async Task<bool> DelFile(string Path)
        {
            var ret = await DelFileForAliYunOSS(Path);
            return ret;
        }
        #region 阿里云上传方法(File)
        /// <summary>
        /// 阿里云上传方法(File)
        /// </summary>
        /// <param name="options"></param>
        /// <param name="fileExt"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<string> UpLoadFileForAliYunOSS(string fileExt, IFormFile file)
        {
            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 = App.Configuration["FileUploadOptions:SavePath"] + today + "/" + newFileName; //云文件保存路径
            //初始化阿里云配置--外网Endpoint、访问ID、访问password
            var aliYun = new OssClient(App.Configuration["FileUploadOptions:AliOSSEndpoint"], App.Configuration["FileUploadOptions:AliOSSAccessKeyID"], App.Configuration["FileUploadOptions:AliOSSAccessKeySecret"]);
            //将文件md5值赋值给meat头信息,服务器验证文件MD5
            var objectMeta = new ObjectMetadata
            {
                ContentMd5 = md5
            };
            var task = Task.Run(() =>
            //文件上传--空间名、文件保存路径、文件流、meta头信息(文件md5) //返回meta头信息(文件md5)
                aliYun.PutObject(App.Configuration["FileUploadOptions:AliOSSBucketName"], filePath, fileStream, objectMeta)
              );
            //等待完成
            try
            {
                task.Wait();
            }
            catch (AggregateException ex)
            {
                throw Oops.Oh(ex.Message);
            }
            //返回给UEditor的插入编辑器的图片的src
            return App.Configuration["FileUploadOptions:AliOSSSaveBaseUrl"] + filePath;
        }
        #endregion
        #region 阿里云上传方法(Base64)
        /// <summary>
        /// 阿里云上传方法(Base64)
        /// </summary>
        /// <param name="options"></param>
        /// <param name="memStream"></param>
        /// <returns></returns>
        public async Task<string> UpLoadBase64ForAliYunOSS(MemoryStream memStream)
        {
            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 = App.Configuration["FileUploadOptions:SavePath"] + today + "/" + newFileName; //云文件保存路径
                                                                                                        //初始化阿里云配置--外网Endpoint、访问ID、访问password
            var aliYun = new OssClient(App.Configuration["FileUploadOptions:AliOSSEndpoint"], App.Configuration["FileUploadOptions:AliOSSAccessKeyID"], App.Configuration["FileUploadOptions:AliOSSAccessKeySecret"]);
            //将文件md5值赋值给meat头信息,服务器验证文件MD5
            var objectMeta = new ObjectMetadata
            {
                ContentMd5 = md5
            };
            try
            {
                //文件上传--空间名、文件保存路径、文件流、meta头信息(文件md5) //返回meta头信息(文件md5)
                aliYun.PutObject(App.Configuration["FileUploadOptions:AliOSSBucketName"], filePath, fileStream, objectMeta);
            }
            catch (AggregateException ex)
            {
                throw Oops.Oh(ex.Message);
            }
            //返回给UEditor的插入编辑器的图片的src
            return App.Configuration["FileUploadOptions:AliOSSSaveBaseUrl"] + filePath;
        }
        #endregion
        #region 删除文件
        /// <summary>
        /// 阿里云删除
        /// </summary>
        /// <param name="options"></param>
        /// <param name="fileUrl">带xxx.xx的链接地址</param>
        /// <returns></returns>
        public async Task<bool> DelFileForAliYunOSS(string fileUrl)
        {
            //初始化阿里云配置--外网Endpoint、访问ID、访问password
            var aliYun = new OssClient(App.Configuration["FileUploadOptions:AliOSSEndpoint"], App.Configuration["FileUploadOptions:AliOSSAccessKeyID"], App.Configuration["FileUploadOptions:AliOSSAccessKeySecret"]);
            try
            {
                var task = Task.Run(() => aliYun.DeleteObject(App.Configuration["FileUploadOptions:AliOSSBucketName"], (App.Configuration["FileUploadOptions:SavePath"]?.RemoveStartWithStr("/") ?? "") + fileUrl.GetFileName()));
                task.Wait();
            }
            catch (Exception ex)
            {
                throw Oops.Oh(ex.Message);
            }
            //返回给UEditor的插入编辑器的图片的src
            return true;
        }
        #endregion
        #region 识别上传
        public async Task<(IDCardOCRResponse, string)> UpIdCord(string PageName = "FRONT")
        {
            try
            {
                var maxSize = 1024 * 1024 * 5; //上传大小5M
                var FileData = _request?.Form?.Files["file"];
                if (FileData.Length > maxSize)
                {
                    throw Oops.Oh(" 上传文件不可超出500K");
                }
                //处理图形
                //  var FileData = Request.Form.Files[0];
                Image oimage = Image.FromStream(FileData.OpenReadStream());
                if (oimage == null)
                {
                    throw Oops.Oh(" 上传失败");
                }
                MemoryStream ms = new MemoryStream();
                if (oimage.Width > 600)
                {
                    if (oimage.Width > oimage.Height)
                        oimage.GetThumbnailImage(600, 400, null, IntPtr.Zero).Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    else
                        oimage.GetThumbnailImage(400, 600, null, IntPtr.Zero).Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                    oimage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                ms.Position = 0;
                var arr = ms.ToArray();
                string img64 = Convert.ToBase64String(arr);
                IDCardOCRResponse idcordinfo = null;
                string url = "";
                try
                {
                    idcordinfo = _tcs.IdCord(img64, PageName == "FRONT");
                    url = await UploadFilesFByBase64(_tcs.GetIdCordImg());
                    idcordinfo.AdvancedInfo = null;
                    return (idcordinfo, url);
                }
                catch (Exception e)
                {
                    throw Oops.Oh(e.Message);
                }
            }
            catch (Exception e)
            {
                throw Oops.Oh(e.Message);
            }
        }
        public async Task<(BizLicenseOCRResponse, string)> UpBizLicense()
        {
            try
            {
                var maxSize = 1024 * 1024 * 5; //上传大小5M
                var FileData = _request?.Form?.Files["file"];
                if (FileData.Length > maxSize)
                {
                    throw Oops.Oh(" 上传文件不可超出500K");
                }
                //处理图形
                //  var FileData = Request.Form.Files[0];
                Image oimage = Image.FromStream(FileData.OpenReadStream());
                if (oimage == null)
                {
                    throw Oops.Oh(" 上传失败");
                }
                MemoryStream ms = new MemoryStream();
                if (oimage.Width > 600)
                {
                    if (oimage.Width > oimage.Height)
                        oimage.GetThumbnailImage(600, 400, null, IntPtr.Zero).Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    else
                        oimage.GetThumbnailImage(400, 600, null, IntPtr.Zero).Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                    oimage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                ms.Position = 0;
                var arr = ms.ToArray();
                string img64 = Convert.ToBase64String(arr);
                BizLicenseOCRResponse info = null;
                string url = "";
                try
                {
                    info = _tcs.BizLicenseOCR(img64);
                    url = await UploadFilesFByBase64(img64);
                    return (info, url);
                }
                catch (Exception e)
                {
                    throw Oops.Oh(e.Message);
                }
            }
            catch (Exception e)
            {
                throw Oops.Oh(e.Message);
            }
        }
        public async Task<(bool,string)> IaiAddPerso(string CoredID,string Name,int PersonGender)
        {
            try
            {
                var maxSize = 1024 * 1024 * 5; //上传大小5M
                var FileData = _request?.Form?.Files["file"];
                if (FileData.Length > maxSize)
                {
                    throw Oops.Oh(" 上传文件不可超出500K");
                }
                //处理图形
                //  var FileData = Request.Form.Files[0];
                Image oimage = Image.FromStream(FileData.OpenReadStream());
                if (oimage == null)
                {
                    throw Oops.Oh(" 上传失败");
                }
                MemoryStream ms = new MemoryStream();
                if (oimage.Width > 600)
                {
                    if (oimage.Width > oimage.Height)
                        oimage.GetThumbnailImage(600, 400, null, IntPtr.Zero).Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    else
                        oimage.GetThumbnailImage(400, 600, null, IntPtr.Zero).Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                    oimage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                ms.Position = 0;
                var arr = ms.ToArray();
                string img64 = Convert.ToBase64String(arr);
                bool  info = false;
                string url = "";
                try
                {
                    info =  _tcs.IaiAddPerso(img64, CoredID, Name, PersonGender);
                    url = await UploadFilesFByBase64(img64);
                    return (info, url);
                }
                catch (Exception e)
                {
                    throw Oops.Oh(e.Message);
                }
            }
            catch (Exception e)
            {
                throw Oops.Oh(e.Message);
            }
        }
/// <inheritdoc/>
        public async Task<(bool, string)> IaiAddPerso(string imgBase64, string CoredID, string Name, int PersonGender)
        {
            if (string.IsNullOrEmpty(imgBase64))
            {
                throw Oops.Oh("没有内容");
            }
            //检查上传大小
            if (!CommonHelper.CheckBase64Size(imgBase64, 5))
            {
                throw Oops.Oh("上传文件大小超过限制,最大允许上传" + "5" + "M");
            }
            imgBase64 = imgBase64.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
            bool info = false;
            string url = "";
            try
            {
                info = _tcs.IaiAddPerso(imgBase64, CoredID, Name, PersonGender);
                url = await UploadFilesFByBase64(imgBase64);
                return (info, url);
            }
            catch (Exception e)
            {
                throw Oops.Oh(e.Message);
            }
        }
        #endregion
    }
}