//[ValidateAntiForgeryToken]
        //[AjaxOnly]
        public ActionResult SaveForm(int keyValue, dm_task_person_settingEntity entity)
        {
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

            if (files.Count > 0)
            {
                HttpPostedFile pic_file = files[0];
                if (pic_file.ContentLength != 0 && !string.IsNullOrEmpty(pic_file.FileName))
                {
                    UserInfo userInfo = LoginUserInfo.Get();

                    dm_basesettingEntity dm_BasesettingEntity = dM_BaseSettingIBLL.GetEntityByCache(userInfo.companyId);

                    if (dm_BasesettingEntity.IsEmpty())
                    {
                        return(Fail("获取配置信息错误,请检查账号是否正确!"));
                    }

                    entity.typeimage = OSSHelper.PutObject(dm_BasesettingEntity, "TaskCenterIcon/" + Guid.NewGuid().ToString() + Path.GetExtension(pic_file.FileName), pic_file);
                }
            }

            dM_Task_Person_SettingIBLL.SaveEntity(keyValue, entity);
            return(Success("保存成功!"));
        }
        public ActionResult UploadFile1(int keyValue, string ImgBase64, dm_friend_circleEntity entity)
        {
            string[] files = ImgBase64.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
            if (files.Length > 0)
            {
                UserInfo userInfo = LoginUserInfo.Get();
                userInfo.companyId = "e2b3ec3a-310b-4ab8-aa81-b563ac8f3006";

                List <CircleImage> imageList = new List <CircleImage>();
                for (int i = 0; i < files.Length; i++)
                {
                    string image = OSSHelper.PutBase64(dM_BaseSettingIBLL.GetEntityByCache(userInfo.companyId), "", files[i]);
                    imageList.Add(new CircleImage
                    {
                        Image          = image,
                        ThumbnailImage = image + "?x-oss-process=image/resize,w_100,m_lfit"//
                    });
                }

                entity.createcode = userInfo.userId;
                entity.t_status   = 1;
                entity.t_type     = 1;
                entity.t_images   = Newtonsoft.Json.JsonConvert.SerializeObject(imageList);
                dm_friend_circleIBLL.SaveEntity(keyValue, entity);
            }
            return(Success("保存成功。"));
        }
Exemplo n.º 3
0
        public ActionResult UploadFile(int keyValue, dm_articleEntity entity)
        {
            entity.content = HttpUtility.UrlDecode(entity.content);
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

            if (files.Count > 0)
            {
                if (files[0].ContentLength == 0 || string.IsNullOrEmpty(files[0].FileName))
                {
                    return(HttpNotFound());
                }
                UserInfo userInfo = LoginUserInfo.Get();

                /*string FileEextension = Path.GetExtension(files[0].FileName);
                 * string virtualPath = $"/Resource/GoodImage/{Guid.NewGuid().ToString()}{FileEextension}";
                 * string fullFileName = base.Server.MapPath("~" + virtualPath);
                 * string path = Path.GetDirectoryName(fullFileName);
                 * Directory.CreateDirectory(path);
                 * files[0].SaveAs(fullFileName);
                 * entity.a_image = virtualPath;*/
                string appid = userInfo.IsEmpty() ? "e2b3ec3a-310b-4ab8-aa81-b563ac8f3006" : userInfo.companyId;
                entity.a_image = OSSHelper.PutObject(dM_BaseSettingIBLL.GetEntityByCache(appid), "", files[0]);
            }
            dM_ArticleIBLL.SaveEntity(keyValue, entity);
            return(Success("保存成功。"));
        }
        string GeneralShareImage(dm_basesettingEntity dm_BasesettingEntity, string bj_image_path, Bitmap qrCode, int width = 260, int height = 980)
        {
            System.Drawing.Image imgSrc = System.Drawing.Image.FromFile(bj_image_path);
            using (Graphics g = Graphics.FromImage(imgSrc))
            {
                //画专属推广二维码
                g.DrawImage(qrCode, new Rectangle(width,  //-450这个数,越小越靠左,可以调整二维码在背景图的位置
                                                  height, //同理-650越小越靠上
                                                  qrCode.Width,
                                                  qrCode.Height),
                            0, 0, qrCode.Width, qrCode.Height, GraphicsUnit.Pixel);

                //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                //g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //画头像
                //g.DrawImage(titleImage, 8, 8, titleImage.Width, titleImage.Height);
            }

            string basePath = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd("\\".ToCharArray());
            string path1    = basePath + @"/Resource/ShareImage/MeetingDefault1.jpg";

            using (System.IO.FileStream fs = new System.IO.FileStream(path1, FileMode.Create))
            {
                imgSrc.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            string oss_url = OSSHelper.PutObject(dm_BasesettingEntity, "", path1);

            return(oss_url);
        }
        public ActionResult UploadFile(int keyValue, dm_bannerEntity entity)
        {
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

            if (files.Count > 0)
            {
                if (files[0].ContentLength == 0 || string.IsNullOrEmpty(files[0].FileName))
                {
                    return(HttpNotFound());
                }
                UserInfo userInfo = LoginUserInfo.Get();

                /*string FileEextension = Path.GetExtension(files[0].FileName);
                 * string virtualPath = $"/Resource/GoodImage/{Guid.NewGuid().ToString()}{FileEextension}";
                 * string fullFileName = base.Server.MapPath("~" + virtualPath);
                 * string path = Path.GetDirectoryName(fullFileName);
                 * Directory.CreateDirectory(path);
                 * files[0].SaveAs(fullFileName);
                 * entity.b_image = virtualPath;*/

                entity.b_image = OSSHelper.PutObject(dM_BaseSettingIBLL.GetEntityByCache(userInfo.companyId), "", files[0]);
            }
            dM_BannerIBLL.SaveEntity(keyValue, entity);
            return(Success("保存成功。"));
        }
Exemplo n.º 6
0
        public ActionResult UploadImageByAliSingle()
        {
            try
            {
                string appid = CheckAPPID();
                dm_basesettingEntity dm_BasesettingEntity = dm_BaseSettingIBLL.GetEntityByCache(appid);

                if (System.Web.HttpContext.Current.Request.Files.Count != 1)
                {
                    return(Fail("请上传一张图片!"));
                }

                HttpPostedFile pic_file = System.Web.HttpContext.Current.Request.Files[0];
                if (pic_file.ContentLength == 0 || string.IsNullOrEmpty(pic_file.FileName))
                {
                    return(HttpNotFound());
                }

                string key = DateTime.Now.ToString("yyyyMMdd") + "/" + Guid.NewGuid().ToString() + Path.GetExtension(pic_file.FileName);

                string putUrl = OSSHelper.PutObject(dm_BasesettingEntity, "", pic_file);
                //string putUrl = PutObject(dm_BasesettingEntity.oss_accesskeyid, dm_BasesettingEntity.oss_accesskeysecret, dm_BasesettingEntity.oss_endpoint, dm_BasesettingEntity.oss_buketname, key, pic_file.InputStream);

                return(Success("上传成功", new { ImageUrl = putUrl }));
            }
            catch (Exception ex)
            {
                return(FailException(ex));
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// 从缓存根据对象名获取文件地址
 /// </summary>
 /// <param name="objectname"></param>
 /// <returns></returns>
 public static string GetFile(string objectname)
 {
     lock (GetFileObject)
     {
         try
         {
             var filecache = files.OrderByDescending(t => t.expiretime).FirstOrDefault(t => t.objectname == objectname);
             if (filecache == null || filecache.expiretime < DateTime.Now.AddMinutes(3))
             {
                 OSSHelper oSSHelper  = new OSSHelper();
                 DateTime  expireTime = DateTime.Now.AddMinutes(30);
                 string    ossurl     = oSSHelper.GetFilePath(objectname, expireTime);
                 using (brnshopEntities context = new brnshopEntities())
                 {
                     var bsp_file = context.bsp_files.SingleOrDefault(t => t.objectname == objectname);
                     bsp_file.ossurl = ossurl;
                     if (filecache == null)
                     {
                         FileCacheModel newfilecache = new FileCacheModel();
                         newfilecache.expiretime   = expireTime;
                         newfilecache.objectname   = objectname;
                         newfilecache.ossurl       = ossurl;
                         newfilecache.requestcount = 1;
                         newfilecache.timestamp    = bsp_file.timestamp;
                         files.Add(newfilecache);
                         //if(files.Count() > 999)
                         //{
                         //    files.RemoveAt(0);
                         //}//控制filecache数量
                     }
                     else
                     {
                         filecache.ossurl     = ossurl;
                         filecache.expiretime = expireTime;
                         filecache.requestcount++;
                         bsp_file.requestcount += filecache.requestcount;
                         filecache.requestcount = 0;
                     }
                     context.SaveChanges();
                 }
                 Logger._.Info(files.Count.ToString());
                 return(ossurl);
             }//缓存中没有或三分钟内要过期就请求oss获取地址存入缓存和数据库
             else
             {
                 filecache.requestcount++;
                 return(filecache.ossurl);
             }
         }
         catch (Exception ex)
         {
             Logger._.Error(ex);
             return("");
         }
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public async Task<IHttpActionResult> Post()
        {

            try
            {
                string fileName = Guid.NewGuid().ToString();
                string fileOrginalFile = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");                 
                string fileResized800Name = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");
                System.Drawing.Bitmap image = new System.Drawing.Bitmap(HttpContext.Current.Request.InputStream);
                image.Save(fileOrginalFile);
                using (var imageFactory = new ImageFactory(preserveExifData: true))
                {
                    System.Drawing.Size size = new System.Drawing.Size(800, 1600);
                    ResizeLayer resize = new ResizeLayer(size, ResizeMode.Max);
              
                    imageFactory.Load(fileOrginalFile).Resize(resize).Save(fileResized800Name);
                }
                OSSHelper blob = new OSSHelper(AIHE.WebApi.Helpers.UtilityString.BlobString.YiQiHeHe);
              //  BlobHelper blob = new BlobHelper(BlobString.Portrait);
                string contentType = "image/jpeg";

               
                  blob.UploadFile(fileResized800Name, fileName, contentType);

                //删除文件
                File.Delete(fileOrginalFile);

                File.Delete(fileResized800Name);

                return Json(new ResponseMessageModel(new
                {
                    ImageName = fileName,
                    ImageUrl = CacheObjectHelper.SystemConfig.url_blob + fileName
                }));

          

            }

            catch (Exception ex)
            {
                return Json(new
                {
                    Code = 10,
                    Message = "上传失败"

                });
            }

        }
Exemplo n.º 9
0
 public ActionResult FileUpload(RegistrationModel mRegister)
 {
     //Check server side validation using data annotation
     if (ModelState.IsValid)
     {
         //TO:DO
         var fileName = Path.GetFileName(mRegister.file.FileName);
         var path     = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
         mRegister.file.SaveAs(path);
         var success = OSSHelper.Upload("cddt", "Content/Images/" + fileName, path);
         ViewBag.Message = "File has been uploaded successfully";
         ModelState.Clear();
     }
     return(RedirectToAction("Index"));
 }
Exemplo n.º 10
0
        public ActionResult UploadFile(int keyValue, dm_task_typeEntity entity)
        {
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

            if (files.Count > 0)
            {
                HttpPostedFile pic_file = files[0];
                if (pic_file.ContentLength != 0 && !string.IsNullOrEmpty(pic_file.FileName))
                {
                    UserInfo userInfo = LoginUserInfo.Get();
                    entity.image = OSSHelper.PutObject(dM_BaseSettingIBLL.GetEntityByCache(userInfo.companyId), "", files[0]);
                }
            }
            dM_Task_TypeIBLL.SaveEntity(keyValue, entity);
            return(Success("保存成功。"));
        }
Exemplo n.º 11
0
        public ActionResult UploadFile(int keyValue, dm_level_remarkEntity entity)
        {
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

            if (files.Count > 0)
            {
                if (files[0].ContentLength == 0 || string.IsNullOrEmpty(files[0].FileName))
                {
                    return(HttpNotFound());
                }
                UserInfo userInfo = LoginUserInfo.Get();

                entity.RemarkImage = OSSHelper.PutObject(dM_BaseSettingIBLL.GetEntityByCache(userInfo.companyId), "", files[0]);
            }
            dm_level_remarkIBLL.SaveEntity(keyValue, entity);
            return(Success("保存成功。"));
        }
        public ActionResult UploadFile(int keyValue, dm_versionEntity entity)
        {
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

            if (files.Count > 0)
            {
                if (files[0].ContentLength == 0 || string.IsNullOrEmpty(files[0].FileName))
                {
                    return(HttpNotFound());
                }
                UserInfo userInfo = LoginUserInfo.Get();

                HttpPostedFile httpPostedFile = files[0];
                entity.App_Name = httpPostedFile.FileName;

                entity.App_DownLoad = OSSHelper.PutObject(dM_BaseSettingIBLL.GetEntityByCache(userInfo.companyId), "", httpPostedFile);
            }
            dm_versionIBLL.SaveEntity(keyValue, entity);
            return(Success("保存成功。"));
        }
        public ActionResult UploadFile(int keyValue, string ImgBase64, dm_friend_circleEntity entity)
        {
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

            if (files.Count > 0)
            {
                if (files[0].ContentLength == 0 || string.IsNullOrEmpty(files[0].FileName))
                {
                    return(HttpNotFound());
                }

                UserInfo userInfo = LoginUserInfo.Get();
                userInfo.companyId = "e2b3ec3a-310b-4ab8-aa81-b563ac8f3006";
                dm_basesettingEntity dm_BasesettingEntity = dM_BaseSettingIBLL.GetEntityByCache(userInfo.companyId);

                string[]           files_base64 = ImgBase64.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
                List <CircleImage> imageList    = new List <CircleImage>();
                for (int i = 0; i < files_base64.Length; i++)
                {
                    string image = OSSHelper.PutBase64(dm_BasesettingEntity, "", files_base64[i]);
                    imageList.Add(new CircleImage
                    {
                        Image          = image,
                        ThumbnailImage = image + "?x-oss-process=image/resize,w_100,m_lfit"//
                    });
                }

                entity.t_title_page = OSSHelper.PutObject(dm_BasesettingEntity, "", files[0]);

                entity.createcode = userInfo.userId;
                entity.t_status   = 1;
                entity.t_type     = 1;
                entity.t_images   = Newtonsoft.Json.JsonConvert.SerializeObject(imageList);
                dm_friend_circleIBLL.SaveEntity(keyValue, entity);
                return(Success("保存成功。"));
            }
            else
            {
                return(Fail("请上传封面图片!"));
            }
        }
Exemplo n.º 14
0
        public ResultModel Upload(byte[] content, string filename, string client)
        {
            OSSHelper osshelper  = new OSSHelper();
            var       suffixname = filename.Split('.')[filename.Split('.').Length - 1];
            var       timestamp  = EncryptHelp.GetTimeStamp();
            var       objectName = EncryptHelp.GetRandomStr(4) + timestamp + "." + suffixname;

            if (!osshelper.Upload(content, filename, objectName, OSSHelper.GetContentTypeBySuffix(suffixname)))
            {
                return(ResultModel.Error("oss文件上传失败,请联系管理员"));
            }
            using (brnshopEntities context = new brnshopEntities())
            {
                try
                {
                    bsp_files newfile = new bsp_files();
                    newfile.client       = client;
                    newfile.name         = filename;
                    newfile.ossurl       = "";
                    newfile.requesturl   = "";
                    newfile.suffixname   = suffixname;
                    newfile.timestamp    = timestamp;
                    newfile.uploadtime   = DateTime.Now;
                    newfile.objectname   = objectName;
                    newfile.requestcount = 0;
                    newfile.domain       = ConfigurationManager.AppSettings["filedomain"];
                    context.bsp_files.Add(newfile);
                    context.SaveChanges();

                    //DateTime expirationTime = DateTime.Now.AddMinutes(30);
                    //GetFilePath(objectName);
                    return(ResultModel.Success(newfile.domain + newfile.objectname));
                }
                catch (Exception ex)
                {
                    Logger._.Error(ex);
                    return(ResultModel.Error(ex.ToString()));
                }
            }
        }
Exemplo n.º 15
0
        public ActionResult UploadImageByAliMutiple()
        {
            List <string> images = new List <string>();

            try
            {
                string appid = CheckAPPID();
                dm_basesettingEntity dm_BasesettingEntity = dm_BaseSettingIBLL.GetEntityByCache(appid);

                if (System.Web.HttpContext.Current.Request.Files.Count <= 0)
                {
                    return(Fail("请上传至少一张图片!"));
                }

                HttpFileCollection httpFileCollection = System.Web.HttpContext.Current.Request.Files;
                for (int i = 0; i < httpFileCollection.Count; i++)
                {
                    HttpPostedFile pic_file = httpFileCollection[i];

                    #region 头像上传
                    if (pic_file.ContentLength == 0 || string.IsNullOrEmpty(pic_file.FileName))
                    {
                        return(HttpNotFound());
                    }
                    #endregion


                    //string putUrl = PutObject(dm_BasesettingEntity.oss_accesskeyid, dm_BasesettingEntity.oss_accesskeysecret, dm_BasesettingEntity.oss_endpoint, dm_BasesettingEntity.oss_buketname, key, pic_file.InputStream);
                    string putUrl = OSSHelper.PutObject(dm_BasesettingEntity, "", pic_file);

                    images.Add(putUrl);
                }

                return(Success("上传成功", new { ImageUrls = images }));
            }
            catch (Exception ex)
            {
                return(FailException(ex));
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// 获取文件信息(路径)
        /// </summary>
        /// <param name="rootPath">文件根目录</param>
        /// <param name="fileId">文件Id</param>
        /// <param name="rev">版本</param>
        /// <returns>文件信息</returns>
        public string SingleFileDownload(string rootPath, string fileId, string rev, string token)
        {
            try
            {
                EASAPIModel model = GetAPIModel(token);

                // 设置传参
                SingleDownloadReq body     = new SingleDownloadReq();
                string            savePath = $"{rootPath}\\Files\\{fileId}";
                if (!string.IsNullOrEmpty(rev))
                {
                    body.Rev = rev;
                    savePath = $"{savePath}/{rev}";
                }
                body.Docid    = model.DocId;
                body.SavePath = savePath;
                body.Usehttps = false;

                // 文件信息
                string resBody    = GetFileDownloadResponse(body, model);
                var    dynamicObj = JsonConvert.DeserializeObject <dynamic>(resBody);
                string method     = dynamicObj["authrequest"][0].Value;
                string url        = dynamicObj["authrequest"][1].Value;
                string fileName   = dynamicObj["name"].Value;
                string filePath   = $"{savePath}\\{fileName}";

                //如果不存在,创建它
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }

                List <string> headers = new List <string>();
                for (int i = 2; i < dynamicObj["authrequest"].Count; ++i)
                {
                    headers.Add(dynamicObj["authrequest"][i].Value);
                }

                OSSHelper       ossHttpHelper = new OSSHelper();
                HttpWebResponse ossResult     = ossHttpHelper.SendReqToOSS(method, url, headers, null);

                Stream    fileContent = ossResult.GetResponseStream();
                const int bufferLen   = 50 * 1024 * 1024;

                if (File.Exists(filePath))
                {
                    //写入数据
                    using (FileStream fs = new FileStream(filePath, FileMode.Truncate))
                    {
                        byte[] buffer = new byte[bufferLen];
                        int    count  = 0;
                        while ((count = fileContent.Read(buffer, 0, bufferLen)) > 0)
                        {
                            fs.Write(buffer, 0, count);
                        }
                        fs.Dispose();
                    }
                }
                else
                {
                    //写入数据
                    using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
                    {
                        byte[] buffer = new byte[bufferLen];
                        int    count  = 0;
                        while ((count = fileContent.Read(buffer, 0, bufferLen)) > 0)
                        {
                            fs.Write(buffer, 0, count);
                        }
                        fs.Dispose();
                    }
                }

                return(filePath);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 获取文件信息(路径)
        /// </summary>
        /// <param name="rootPath">文件根目录</param>
        /// <param name="fileId">文件Id</param>
        /// <returns>文件信息</returns>
        public string SingleFileDownload(string rootPath, string fileId, string token)
        {
            // 调用接口
            try
            {
                string resBody    = GetShareFileDownloadResponse(token);
                var    dynamicObj = JsonConvert.DeserializeObject <dynamic>(resBody);
                string method     = dynamicObj["authrequest"][0].Value;
                string url        = dynamicObj["authrequest"][1].Value;
                string fileName   = dynamicObj["name"].Value;

                string savePath = $"{rootPath}\\Files\\{fileId}";
                string filePath = $"{savePath}\\{fileName}";

                //如果不存在,创建它
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }

                OSSHelper       ossHttpHelper = new OSSHelper();
                HttpWebResponse ossResult     = ossHttpHelper.SendReqToOSS(method, url, new List <string>(), null);

                Stream    fileContent = ossResult.GetResponseStream();
                const int bufferLen   = 50 * 1024 * 1024;

                if (File.Exists(filePath))
                {
                    //写入数据
                    using (FileStream fs = new FileStream(filePath, FileMode.Truncate))
                    {
                        byte[] buffer = new byte[bufferLen];
                        int    count  = 0;
                        while ((count = fileContent.Read(buffer, 0, bufferLen)) > 0)
                        {
                            fs.Write(buffer, 0, count);
                        }
                        fs.Dispose();
                    }
                }
                else
                {
                    //写入数据
                    using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
                    {
                        byte[] buffer = new byte[bufferLen];
                        int    count  = 0;
                        while ((count = fileContent.Read(buffer, 0, bufferLen)) > 0)
                        {
                            fs.Write(buffer, 0, count);
                        }
                        fs.Dispose();
                    }
                }

                return(filePath);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// 实名认证提交
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="name"></param>
        /// <param name="cardno"></param>
        /// <param name="CertificaRecordID"></param>
        /// <returns></returns>

        public ActionResult Certification(int User_ID, string name, string cardno, string facecard = "", string frontcard = "")
        {
            try
            {
                string appid = CheckAPPID();
                if (User_ID <= 0)
                {
                    return(FailNoLogin());
                }

                if (name.IsEmpty())
                {
                    throw new Exception("真实姓名不能为空!");
                }
                //dm_certifica_recordEntity dm_Certifica_RecordEntity = new dm_certifica_recordEntity();
                dm_basesettingEntity dm_BasesettingEntity = dm_BaseSettingIBLL.GetEntityByCache(appid);

                dm_certifica_recordEntity dm_Certifica_RecordEntity = dm_CertificaRecordIBLL.GetCertificationRecord(User_ID);
                if (dm_Certifica_RecordEntity.IsEmpty())
                {
                    dm_Certifica_RecordEntity = new dm_certifica_recordEntity();
                }
                else
                {
                    if (dm_Certifica_RecordEntity.realstatus == 0)
                    {
                        throw new Exception("实名认证信息正在审核中,请勿重复提交!");
                    }
                    else if (dm_Certifica_RecordEntity.realstatus == 1)
                    {
                        throw new Exception("实名认证信息已审核通过!");
                    }
                }

                #region 身份证正面上传
                if (facecard.IsEmpty() || facecard == "System.Web.HttpPostedFileWrapper")
                {
                    HttpPostedFile facecard_file = System.Web.HttpContext.Current.Request.Files["facecard"];
                    if (facecard_file.IsEmpty() || facecard_file.ContentLength == 0 || string.IsNullOrEmpty(facecard_file.FileName))
                    {
                        throw new Exception("请上传身份证正面照片!");
                    }
                    dm_Certifica_RecordEntity.facecard = OSSHelper.PutObject(dm_BasesettingEntity, "", facecard_file);
                }
                else
                {
                    dm_Certifica_RecordEntity.facecard = facecard;
                }
                #endregion


                #region 身份证反面上传
                if (frontcard.IsEmpty() || frontcard == "System.Web.HttpPostedFileWrapper")
                {
                    HttpPostedFile frontcard_file = System.Web.HttpContext.Current.Request.Files["frontcard"];
                    if (frontcard_file.IsEmpty() || frontcard_file.ContentLength == 0 || string.IsNullOrEmpty(frontcard_file.FileName))
                    {
                        throw new Exception("请上传身份证反面照片!");
                    }

                    dm_Certifica_RecordEntity.frontcard = OSSHelper.PutObject(dm_BasesettingEntity, "", frontcard_file);
                }
                else
                {
                    dm_Certifica_RecordEntity.frontcard = frontcard;
                }
                #endregion

                #region 构造其他信息
                dm_Certifica_RecordEntity.user_id    = User_ID;
                dm_Certifica_RecordEntity.realname   = name;
                dm_Certifica_RecordEntity.cardno     = cardno;
                dm_Certifica_RecordEntity.realstatus = 0;
                dm_Certifica_RecordEntity.appid      = appid;
                #endregion

                dm_CertificaRecordIBLL.SaveEntity(dm_Certifica_RecordEntity.id, dm_Certifica_RecordEntity);

                return(Success("提交成功!"));
            }
            catch (Exception ex)
            {
                return(FailException(ex));
            }
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public async Task<IHttpActionResult> Post()
        {
            try
            {
                if (!HttpContext.Current.Request.Form.HasKeys())
                {
                    CommonRequestHelper.ThrowErrorMessage("上传失败");
                }

                DataBaseEntities db = new DataBaseEntities();
                OSSHelper blob = new OSSHelper(AIHE.WebApi.Helpers.UtilityString.BlobString.YiQiHeHe);

              
                switch (HttpContext.Current.Request.Files.Count)
                {
                    case 0:
                        {
                            var news0 = new tb_JiuYouQuan
                            {
                                AddDate = UtilityHelper.getNow(),
                                Description = HttpContext.Current.Request.Form["content"],
                                id = Guid.NewGuid().ToString(),
                                IsHot = false,
                                Islegal = true,
                                SingleHeight = 0,
                                SingleWidth = 0,
                                UserId = User.Identity.GetUserId(),
                                Images = ""
                            };
                            db.tb_JiuYouQuan.Add(news0);
                            db.SaveChanges();
                       
                            return Json(new ResponseMessageModel(true));


                        }
                      
                        break;
                    case 1:
                        //只有一个文件
                        #region
                        string fileOrginalFile = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");

                        HttpContext.Current.Request.Files[0].SaveAs(fileOrginalFile);
                        Image pic = Image.FromFile(fileOrginalFile);//strFilePath是该图片的绝对路径
                        int intWidth = pic.Width;//长度像素值
                        int intHeight = pic.Height;//高度像素值 
                        int newWidth = intWidth;
                        int newHeight = intHeight;
                        string fileResizedName = HttpContext.Current.Server.MapPath("/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");
                        string saveFileName = Guid.NewGuid().ToString();
                          blob.UploadFile(fileOrginalFile, saveFileName + "-big");


                        if (intWidth > 135 || intHeight > 135)
                        {
                            using (var imageFactory = new ImageFactory(preserveExifData: true))
                            {


                                if (intWidth > intHeight)
                                {
                                    newWidth = 135;
                                    newHeight = (int)(Convert.ToDouble(intHeight) / Convert.ToDouble(intWidth) * 135);
                                }
                                else
                                {
                                    newHeight = 135;
                                    newWidth = (int)(Convert.ToDouble(intWidth) / Convert.ToDouble(intHeight) * 135);
                                }

                                System.Drawing.Size size = new System.Drawing.Size(newWidth * 2, newHeight * 2);
                                imageFactory.Load(fileOrginalFile).Resize(size).Save(fileResizedName);
                            }
                              blob.UploadFile(fileResizedName, saveFileName);  //缩略图应该是同步程序
                        }
                        else
                        {
                              blob.UploadFile(fileOrginalFile, saveFileName);   //缩略图应该是同步程序
                        }

                        var news1 = new tb_JiuYouQuan
                        {
                            AddDate = UtilityHelper.getNow(),
                            Description = HttpContext.Current.Request.Form["content"],
                            id = Guid.NewGuid().ToString(),
                            Images = saveFileName,
                            IsHot = false,
                            Islegal = true,
                            SingleHeight = newHeight,
                            SingleWidth = newWidth,
                            UserId = User.Identity.GetUserId()
                        };
                        pic.Dispose();
                        File.Delete(fileOrginalFile);

                        File.Delete(fileResizedName);
                        db.tb_JiuYouQuan.Add(news1);
                        db.SaveChanges();
                        return Json(new ResponseMessageModel(true));

                    //删除文件

                        #endregion

                    default:
                        List<string> newsFiles = new List<string>();
                        for (var i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                        {
                            var savedName = Guid.NewGuid().ToString();
                            var fileCropName = HttpContext.Current.Server.MapPath("/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");
                            var orginal = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");
                            HttpContext.Current.Request.Files[i].SaveAs(orginal);
                              blob.UploadFile(orginal, savedName + "-big");

                            using (var imageFactory = new ImageFactory(preserveExifData: true))
                            {
                                // Do your magic here
                                System.Drawing.Size size = new System.Drawing.Size(70 *2, 70*2);
                                ResizeLayer resize = new ResizeLayer(size, ResizeMode.Crop);
                                imageFactory.Load(orginal).Resize(resize).Save(fileCropName);
                            }
                            bool flagCrop =   blob.UploadFile(fileCropName, savedName);

                            if (flagCrop)
                            {
                                newsFiles.Add(savedName);

                            }
                            File.Delete(orginal);

                            File.Delete(fileCropName);

                        }

                        if (newsFiles.Count == 0)
                        {

                            CommonRequestHelper.ThrowErrorMessage("上传失败");
                        }
                       


                            var newsMultiple = new tb_JiuYouQuan
                            {
                                AddDate = UtilityHelper.getNow(),
                                Description = HttpContext.Current.Request.Form["content"],
                                id = Guid.NewGuid().ToString(),
                                Images = string.Join(";", newsFiles),
                                IsHot = false,
                                Islegal = true,
                                SingleHeight = 0,
                                SingleWidth = 0,
                                UserId = User.Identity.GetUserId()
                            };
                            db.tb_JiuYouQuan.Add(newsMultiple);
                            db.SaveChanges();

                       

                              return Json(new ResponseMessageModel(true));
                      

                        break;

                }




            }

            catch (Exception ex)
            {
                
                CommonRequestHelper.ThrowErrorMessage("上传失败");
                return null;
            }
        }
Exemplo n.º 20
0
 public FileUploadDownloadServiceImpl( )
 {
     ossHttpHelper = new OSSHelper();
 }