zoukankan      html  css  js  c++  java
  • ImageUploadAssist--Biz_UploadImageBase

     public class Biz_UploadImageBase
        {
    
            protected moto_imgDAL dal = new moto_imgDAL();
    
    
            #region MethodHelper
    
            /// <summary>
            /// 返回客户端错误
            /// </summary>
            /// <param name="msg"></param>
            /// <returns></returns>
            protected dataresult return_CustomError(string msg)
            {
                return new dataresult
                {
                    msg = msg,
                    code = "-1"
                };
            }
    
            /// <summary>
            /// 包装参数
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="t"></param>
            /// <param name="ignoreProperty"></param>
            /// <param name="ignoreDataProperty"></param>
            /// <returns></returns>
            public string PackagingParam<T>(T t, string ignoreProperty, string ignoreDataProperty)
            {
                string tStr = string.Empty;
                if (t == null)
                {
                    return tStr;
                }
                System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
    
                if (properties.Length <= 0)
                {
                    return tStr;
                }
    
                //按字符排序拼凑 ABCDEF....
                var sortProperties = from item in properties
                                     orderby item.Name
                                     select item;
    
    
                foreach (System.Reflection.PropertyInfo item in sortProperties)
                {
                    string name = item.Name;
                    object value = item.GetValue(t, null);
                    if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                    {
    
                        if (value == null) continue;
                        string strValue = value.ToString().Trim();
    
                        if (strValue != "0" && strValue != "" && !name.Equals(ignoreProperty) && !name.Equals(ignoreDataProperty))
                            tStr += string.Format("{0}={1}&", name, value);
                    }
                    else
                    {
                        PackagingParam(value, ignoreProperty, ignoreDataProperty);
                    }
                }
                return tStr;
            }
    
    
    
            public static string Decode(string strValue)
            {
                return System.Web.HttpUtility.UrlDecode(strValue, Encoding.UTF8);
            }
    
    
            /// <summary>
            /// 指定长度随机数
            /// </summary>
            /// <param name="length"></param>
            /// <param name="prefix">前缀</param>
            /// <returns></returns>
            public string GetRnd(int length, string prefix)
            {
                byte[] b = new byte[4];
                new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
                Random r = new Random(BitConverter.ToInt32(b, 0));
                string s = null,
                str = "0123456789";
                for (int i = 0; i < length - prefix.Length; i++)
                {
                    s += str.Substring(r.Next(0, str.Length - 1), 1);
                }
    
                s = prefix + s;
                return s;
            }
    
            #endregion
    
            #region RunRobots
    
            /// <summary>
            /// 验证方式
            /// </summary>
            /// <param name="json"></param>
            /// <returns></returns>
            protected bool VerifySign(JsonUploadImageData json)
            {
                //所有非空参数  除了 @sign外其余参数按字符排序拼凑
                //@sign_str = brand_name=@brand_name&c_req_type=@c_req_type ......
                //判断 @sign == md5(md5(@sign_str)+@sign_key)     //@sign_key 存在配置环境     
                //相等再继续下一步 不相等 则返回异常
    
                string sign_str = PackagingParam(json, "sign", "image_data");
                if (sign_str.Length > 0)
                    sign_str = sign_str.Remove(sign_str.Length - 1);
    
                WriteLogHelper wlHelper = new WriteLogHelper();
    
                wlHelper.WriteToFile("-----------------------------------------");
                wlHelper.WriteToFile(string.Format("VerifySign:{0}", DateTime.Now));
    
                wlHelper.WriteToFile(string.Format("sign_str:{0}", sign_str));
    
                MdFiveHashingHelper mdFive = new MdFiveHashingHelper();
    
                string midFive = mdFive.GetMD5(sign_str).ToLower();
    
                wlHelper.WriteToFile(string.Format("midFive:{0}", midFive));
    
                string sign = mdFive.GetMD5(midFive + ConfigHelper.sign_key);
    
                wlHelper.WriteToFile(string.Format("sign:{0}", sign));
                wlHelper.WriteToFile(string.Format("json.sign:{0}", json.sign));
    
                return sign.ToLower() == json.sign.ToLower();
            }
    
            /// <summary>
            /// 路径生产者
            /// </summary>
            /// <param name="json"></param>
            /// <param name="readFile"></param>
            /// <returns></returns>
            protected PackagingPathEntity PathGenerator(JsonUploadImageData json, string readFile = "")
            {
                // 图片存放路径  images/{@brand_name}/{@req_type}/{@c_req_type}/{YMD}/
                //@c_req_type 如果为空  
                //则路径 images/{@brand_name}/{@req_type}/{YMD}/
    
                PackagingPathEntity pathEntity = new PackagingPathEntity();
                string ymd = DateTime.Now.ToString("yyyyMMdd");
                pathEntity.RelativePath = string.IsNullOrEmpty(json.c_req_type.Trim()) ?
                    string.Format(@"images/{0}/{1}/{2}/", json.brand_name, json.req_type, ymd) :
                    string.Format(@"images/{0}/{1}/{2}/{3}/", json.brand_name, json.req_type, json.c_req_type.Trim(), ymd);
    
                string fileRandom = GetRnd(25, DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_");
    
                if (string.IsNullOrEmpty(readFile))
                    pathEntity.FileName = string.Format("{0}.{1}", fileRandom, json.suffix);
                else
                {
                    int indexSuffix = readFile.IndexOf(".", StringComparison.Ordinal);
    
                    pathEntity.FileName = fileRandom + readFile.Substring(indexSuffix);
                }
    
                pathEntity.UserImgFilePath = ConfigHelper.UserImg_filePath;
    
                //绝对路径
                pathEntity.AbsolutePath = pathEntity.UserImgFilePath + pathEntity.RelativePath;
    
                pathEntity.AbsolutePath = pathEntity.AbsolutePath.Replace("/", @"");
                //全路径(包含路径与文件)
                pathEntity.FullPath = pathEntity.AbsolutePath + pathEntity.FileName;
    
                return pathEntity;
    
            }
    
    
    
    
            /// <summary>
            /// 保存图片到目录
            /// </summary>
            /// <param name="pathEntity"></param>
            /// <param name="imageData"></param>
            /// <param name="pathAndName"></param>
            protected string SaveImageInFile(PackagingPathEntity pathEntity, byte[] imageData, string pathAndName)
            {
                try
                {
                    //创建文件夹
                    if (!Directory.Exists(pathEntity.AbsolutePath))
                    {
                        var directoryInfo = new DirectoryInfo(pathEntity.AbsolutePath);
                        directoryInfo.Create();
                    }
    
                    //图片唯一标示,该code在表中存在则删除原文件再创建
                    if (File.Exists(pathEntity.FullPath))
                        File.Delete(pathEntity.FullPath);
    
                    //删除原来的图片
                    if (!string.IsNullOrEmpty(pathAndName) && File.Exists(pathEntity.UserImgFilePath + pathAndName.Replace("/", @"")))
                        File.Delete(pathEntity.UserImgFilePath + pathAndName);
    
                    using (FileStream fs = new FileStream(pathEntity.FullPath, FileMode.OpenOrCreate))
                    {
                        fs.Write(imageData, 0, imageData.Length);
                    }
                }
                catch (Exception ex)
                {
                    //throw new Exception("保存图片失败!");
                    pathEntity.RelativePath = string.Empty;
                }
    
                return pathEntity.RelativePath;
            }
    
            /// <summary>
            /// 保存进库
            /// </summary>
            /// <param name="json"></param>
            /// <param name="relativePath"></param>
            /// <param name="fileName"></param>
            /// <returns></returns>
            protected ReturnUrlPathEntity SaveInDatabase(JsonUploadImageData json, string relativePath, string fileName, string ip, string pathAndName)
            {
                //并存入对应数据表
                var imgEntity = new moto_imgEntity
                {
                    brand_name = json.brand_name,
                    req_type = json.req_type,
                    req_id = json.req_id,
                    c_req_type = json.c_req_type,
                    //req_ip=json.req_type,
                    domain_name = json.domain_name,
                    operate_name = json.operate_name,
                    short_url = "",
                    file_path = relativePath + fileName,
                    img_code = json.img_code,
                    remark = json.remark,
                    req_ip = ip
                };
    
    
                int executeResult = string.IsNullOrEmpty(pathAndName) ? dal.Create_moto_imgInsert(imgEntity) : dal.Create_moto_imgUpdate(imgEntity.img_code, imgEntity.file_path, pathAndName);
    
                //返回要求的实体
                if (executeResult > 0)
                    return new ReturnUrlPathEntity
                    {
                        file_path = imgEntity.file_path,
                        short_url = imgEntity.short_url
                    };
    
                return null;
            }
    
            #endregion
    
            #region Abandon
    
            /// <summary>
            /// 读图片文件
            /// </summary>
            /// <param name="ih"></param>
            /// <param name="file_path"></param>
            /// <returns></returns>
            protected List<string> LoopReadFile(string file_path)
            {
                //C#遍历指定文件夹中的所有文件 
                DirectoryInfo imageFolder = new DirectoryInfo(file_path);
    
                List<string> fileList = new List<string>();
    
                //遍历文件
                foreach (FileInfo info in imageFolder.GetFiles())
                {
                    //file.Extension
                    ImageHelper.FileExtension fe = ImageHelper.CheckImageFile(info.FullName);
                    if (fe != ImageHelper.FileExtension.VALIDFILE)
                        fileList.Add(info.Name);
                }
    
                return fileList;
            }
    
            #endregion
        }
  • 相关阅读:
    __getattribute__()、__getattr__()、__setattr__()、__delattr__()
    Python: Catch multiple exceptions in one line (except block)
    Python中的__new__和__init__
    使用sphinx生成Python文档
    Windows下干活儿辅助软件
    Python的Descriptor和Property混用
    Solved: Qt Library LNK 2001 staticMetaObject error
    OS sysbench压力测试
    Oracle 数据库 sysbench 压力测试
    MySQL 数据库 Sysbench压力测试
  • 原文地址:https://www.cnblogs.com/FH-cnblogs/p/5711630.html
Copyright © 2011-2022 走看看