Beispiel #1
0
        /// <summary>
        /// 对图片进行等比例压缩,一直压到指定大小之下
        /// </summary>
        /// <param name="file">需压缩的文件</param>
        /// <param name="tsize">大于多少的图片才压,KB</param>
        /// <param name="vpath">虚拟路径</param>
        public void CompressImg(HttpPostedFile file, int tsize, string vpath)
        {
            int imgSize = tsize * 1024;

            vpath = SafeSC.PathDeal(vpath);
            Stream imgStream = file.InputStream;

            System.Drawing.Image img = System.Drawing.Image.FromStream(imgStream);
            Bitmap bmp = new Bitmap(img);

            if (file.ContentLength > imgSize)//开始压缩,计算大小和比率
            {
                double scale  = (double)imgSize / (double)file.ContentLength;
                int    width  = (int)(img.Width * scale);
                int    height = (int)(img.Height * scale);
                bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
                Graphics grap = Graphics.FromImage(bmp);
                grap.Clear(Color.Transparent);
                grap.DrawImage(img, new Rectangle(0, 0, width, height));
                grap.Dispose();
            }
            SaveImg(vpath, bmp);
            bmp.Dispose();
            imgStream.Close();
        }
Beispiel #2
0
 //返回物理路径
 private string PathDeal(string strPath)
 {
     TemplateDir = SiteConfig.SiteOption.TemplateDir;               //   /Template/V3
     if (!string.IsNullOrEmpty(Request.QueryString["setTemplate"])) //带有指定目录的,如方案设置处跳转
     {
         TemplateDir = Request.QueryString["setTemplate"];
     }
     strPath = TemplateDir + strPath;
     strPath = SafeSC.PathDeal(strPath);
     return("/" + strPath.TrimStart('/').Replace("//", "/"));
 }
Beispiel #3
0
        //data:image/png;base64,
        public string ImgToBase64(string vpath)
        {
            string ppath = function.VToP(SafeSC.PathDeal(vpath));

            if (!File.Exists(ppath))
            {
                throw new Exception(vpath + "文件不存在");
            }
            Bitmap bmp = new Bitmap(ppath);

            return(ImgToBase64ByImage(bmp));
        }
Beispiel #4
0
        public string ImgToBase64(string vpath)
        {
            string ppath = function.VToP(SafeSC.PathDeal(vpath));

            if (!File.Exists(ppath))
            {
                throw new Exception(vpath + "文件不存在");
            }
            System.Drawing.Image image = System.Drawing.Image.FromFile(ppath);
            Bitmap bmp = new Bitmap(image, new Size(160, 90));

            return(imgHelp.ImgToBase64ByImage(bmp));
        }
Beispiel #5
0
        /// <summary>
        /// 将Base64转为图片
        /// </summary>
        /// <param name="vpath">带图片名的路径</param>
        /// <param name="imgtxt">Base64字符串</param>
        public void Base64ToImg(string vpath, string base64, ImageFormat format)
        {
            //data:image/png;base64,
            Bitmap bmp = Base64ToImg(base64);

            string ppath = function.VToP(SafeSC.PathDeal(vpath));

            SafeSC.CreateDir(Path.GetDirectoryName(vpath).Replace("\\", "/"));
            bmp.Save(ppath, format);
            //bmp.Save(txtFileName + ".bmp", ImageFormat.Bmp);
            //bmp.Save(txtFileName + ".gif", ImageFormat.Gif);
            //bmp.Save(txtFileName + ".png", ImageFormat.Png);
        }
Beispiel #6
0
        public IActionResult Index()
        {
            string fileVPath = "";

            if (!string.IsNullOrEmpty(VPath))
            {
                fileVPath = SafeSC.PathDeal(VPath);
                if (!fileVPath.ToLower().StartsWith("/uploadfiles/"))
                {
                    return(WriteErr("该目录下的文件不支持预览"));
                }
            }
            else if (!string.IsNullOrEmpty(FileId))
            {
                B_User_Cloud cloudBll = new B_User_Cloud();
                M_User_Cloud cloudMod = cloudBll.SelReturnModel(FileId);
                if (cloudMod == null)
                {
                    return(WriteErr("文件不存在!"));
                }
                fileVPath = cloudMod.VPath + cloudMod.SFileName;
            }
            else
            {
                return(WriteErr("未指定文件"));
            }
            string filePath = function.VToP(fileVPath);
            string exName   = System.IO.Path.GetExtension(fileVPath).ToLower().Replace(".", "");//doc

            if (string.IsNullOrEmpty(exName))
            {
                return(WriteErr("文件无后缀名"));
            }
            if (!System.IO.File.Exists(filePath))
            {
                return(WriteErr("文件[" + fileVPath + "]不存在"));
            }
            if (SafeSC.FileNameCheck(fileVPath))
            {
                return(WriteErr("文件名异常,请去除特殊符号,或更换后缀名"));
            }
            else if (exName.Equals("config"))
            {
                return(WriteErr("该类型文件不提供预览服务!!"));
            }
            /*---------------------------------------------------------------------------------------------------*/
            ViewBag.filePath  = filePath;
            ViewBag.fileVPath = fileVPath;
            ViewBag.exName    = exName;
            return(View());
        }
Beispiel #7
0
        /// <summary>
        /// 将Base64转为图片
        /// </summary>
        /// <param name="vpath">带图片名的路径</param>
        /// <param name="imgtxt">Base64字符串</param>
        public void Base64ToImg(string vpath, string base64)
        {
            //data:image/png;base64,
            if (base64.Contains("base64,"))
            {
                base64 = Regex.Split(base64, Regex.Unescape("base64,"))[1];
            }
            string ppath = function.VToP(SafeSC.PathDeal(vpath));

            SafeSC.CreateDir(ppath);
            byte[]       arr = Convert.FromBase64String(base64);
            MemoryStream ms  = new MemoryStream(arr);
            Bitmap       bmp = new Bitmap(ms);

            bmp.Save(ppath, System.Drawing.Imaging.ImageFormat.Jpeg);
            //bmp.Save(txtFileName + ".bmp", ImageFormat.Bmp);
            //bmp.Save(txtFileName + ".gif", ImageFormat.Gif);
            //bmp.Save(txtFileName + ".png", ImageFormat.Png);
            ms.Close();
        }
Beispiel #8
0
        //下载并存为mht格式
        public string DownToMHT(string url, string vpath)
        {
            if (!url.Contains("://"))
            {
                throw new Exception("地址必须以http或https开头");
            }
            vpath = SafeSC.PathDeal(vpath).Replace("#", "井").Replace("-", "");//去除掉空格等,否则客户端打开会报错
            string ppath = function.VToP(vpath);
            string dir   = Path.GetDirectoryName(ppath);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            CDO.Message       msg = new CDO.MessageClass();
            CDO.Configuration c   = new CDO.ConfigurationClass();
            msg.Configuration = c;
            msg.CreateMHTMLBody(url, CdoMHTMLFlags.cdoSuppressNone, "", "");//cdoSuppressNone=将全部资源都打包进入,CdoMHTMLFlags.cdoSuppressAll=只保留纯页面
            msg.GetStream().SaveToFile(ppath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite);
            return(vpath);
        }
Beispiel #9
0
 //只允许处理/uploadfiles/user/目录下的图片
 private string GetImgPath(string url)
 {
     return(SafeSC.PathDeal("/UploadFiles/User/" + IPath.ToLower().Replace("/uploadfiles/user/", "")));
 }
Beispiel #10
0
        private M_Blog_Msg FillMsg(string msg, out string puremsg, int pid = 0, int rid = 0, string files = "")
        {
            puremsg = msg;
            M_User_Plat upMod = B_User_Plat.GetLogin();
            M_Blog_Msg  model = new M_Blog_Msg();

            model.MsgType = 1;
            model.Status  = 1;
            model.CUser   = upMod.UserID;
            model.CUName  = upMod.TrueName;
            model.ProID   = CurProID;
            model.CompID  = upMod.CompID;
            model.pid     = pid;
            model.ReplyID = rid;
            #region 信息内容处理
            //#话题(转码后会带有#符号,所以需要转码前处理完成)
            if (msg.Contains("#"))
            {
                msg = msg.Replace(deftopic, "");
                string tlp = "<a href='/Plat/Blog?Skey={0}' title='话题浏览'>{1}</a>";
                Dictionary <string, string> itemDic = new Dictionary <string, string>();
                for (int i = 0; !string.IsNullOrEmpty(regHelper.GetValueBySE(msg, "#", "#", false)) && i < 5; i++)//最多不能超过5个话题
                {
                    string topic = "#" + regHelper.GetValueBySE(msg, "#", "#", false) + "#";
                    msg   = msg.Replace(topic, "{" + i + "}");
                    topic = topic.Replace(" ", "").Replace(",", "");
                    itemDic.Add("{" + i + "}", string.Format(tlp, Server.UrlEncode(topic), topic));
                    model.Topic += topic + ",";
                }
                msg = HttpUtility.HtmlEncode(msg);
                foreach (var item in itemDic)
                {
                    msg = msg.Replace(item.Key, item.Value);
                }
            }
            else
            {
                msg = HttpUtility.HtmlEncode(msg);
            }
            //URL转链接
            {
                string          tlp = "<a href='{0}' target='_blank'>{0}</a>";
                MatchCollection mcs = regHelper.GetUrlsByStr(msg);
                foreach (Match m in mcs)
                {
                    //同网址,信息替换多次会产生Bug,如多个www.baidu.com
                    string url = m.Value.IndexOf("://") < 0 ? "http://" + m.Value : m.Value;
                    msg = msg.Replace(m.Value, string.Format(tlp, url));
                }
            }
            //表情
            {
                if (!string.IsNullOrEmpty(ImgFace_Hid.Value))
                {
                    string    imgHtml = "<img src='/Plugins/Ueditor/dialogs/emotion/{0}' class='imgface_img' />";
                    DataTable imgDT   = JsonHelper.JsonToDT(ImgFace_Hid.Value);
                    foreach (DataRow dr in imgDT.Rows)
                    {
                        msg     = msg.Replace(dr["title"].ToString(), string.Format(imgHtml, dr["realurl"].ToString()));
                        puremsg = puremsg.Replace(dr["title"].ToString(), "");
                    }
                }
            }
            //@功能
            {
                MatchCollection mc = regHelper.GetValuesBySE(msg, "@", "]");
                int             id = 0;
                string          atuser = "", atgroup = "", name = "";
                string          uTlp = "<a href='javascript:;' onclick='ShowUser({0});'>{1}</a>";
                string          gTlp = "<a href='javascript:;' onclick='ShowGroup({0});'>{1}</a>";
                foreach (Match m in mc)
                {
                    //@what130[uid:19],名字替换为超链接,之后的取值取入数据库
                    if (string.IsNullOrEmpty(m.Value))
                    {
                        continue;
                    }
                    if (m.Value.Contains("uid:"))
                    {
                        id      = DataConvert.CLng(regHelper.GetValueBySE(m.Value, "uid:", "]", false));
                        name    = regHelper.GetValueBySE(m.Value, "@", @"\[").Replace("[", "");
                        atuser += id + ",";
                        msg     = msg.Replace(m.Value, string.Format(uTlp, id, name));
                    }
                    else if (m.Value.Contains("gid:"))
                    {
                        id       = DataConvert.CLng(regHelper.GetValueBySE(m.Value, "gid:", "]", false));
                        name     = regHelper.GetValueBySE(m.Value, "@", @"\[").Replace("[", "");
                        atgroup += id + ",";
                        msg      = msg.Replace(m.Value, string.Format(gTlp, id, name));
                    }
                    puremsg = puremsg.Replace(m.Value, "");
                }
                if (!string.IsNullOrEmpty(atuser) || !string.IsNullOrEmpty(atgroup))
                {
                    atuser += upBll.SelByGIDS(atgroup);
                    if (!string.IsNullOrEmpty(atuser.Replace(",", "")))
                    {
                        model.ATUser = StrHelper.IdsFormat(atuser);
                        //model.ATUser = model.ATUser.Replace("," + upMod.UserID, "");//过滤自己
                        //提示被@人
                        M_Notify notifyMod = new M_Notify();
                        notifyMod.CUName    = upMod.UserName;
                        notifyMod.Title     = "Hi,[" + B_User.GetUserName(upMod.TrueName, upMod.UserName) + "]@你了,点击查看详情";
                        notifyMod.Content   = puremsg.Length > 30 ? puremsg.Substring(0, 30) : puremsg;
                        notifyMod.ReceUsers = model.ATUser;
                        B_Notify.NotifyList.Add(notifyMod);
                    }
                }
            }
            //--------------------------------
            msg = msg.Replace("\r", "").Replace("\n", "<br/>");//替换换行标识
            #endregion
            //msg = msg.Replace("&#39;", "\'");
            model.MsgContent = msg;
            if (rid > 0)
            {
                M_Blog_Msg msgMod = msgBll.SelReturnModel(model.ReplyID);
                model.ReplyUserID = msgMod.CUser;
                model.ReplyUName  = msgMod.CUName;
            }
            if (string.IsNullOrEmpty(files) && !string.IsNullOrEmpty(Request.Form["Attach_Hid"]))
            {
                files = SafeSC.PathDeal(Request.Form["Attach_Hid"].Trim());
            }
            if (!string.IsNullOrEmpty(files))//为安全,不允许全路径,必须后台对路径处理
            {
                string uppath = B_Plat_Common.GetDirPath(B_Plat_Common.SaveType.Blog);
                foreach (string file in files.Split('|'))
                {
                    if (string.IsNullOrEmpty(file))
                    {
                        continue;
                    }
                    model.Attach += uppath + file + "|";
                }
            }
            if (!string.IsNullOrEmpty(Request.Form["GOnlyMe_Chk"]))
            {
                model.GroupIDS = "0";
            }
            else
            {
                model.GroupIDS = string.IsNullOrEmpty(Request.Form["GroupIDS_Chk"]) ? "" : Request.Form["GroupIDS_Chk"];//后期需加入检测,避免前台伪造
            }
            model.ColledIDS = "";
            return(model);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["vpath"]))
            {
                vpath = Server.UrlDecode(Request["vpath"]);
                while (vpath.Contains("//"))
                {
                    vpath = vpath.Replace("//", "/");
                }
            }
            else if (!string.IsNullOrEmpty(Request["File"]))//Guid,Plat_Doc
            {
                //检测公司等信息
                M_User_Plat upMod   = B_User_Plat.GetLogin();
                B_Plat_File fileBll = new B_Plat_File();
                M_Plat_File fileMod = fileBll.SelReturnModel(Request["File"]);
                if (upMod == null || upMod.UserID == 0)
                {
                    function.WriteErrMsg("你尚未登录能力中心,请先登录!");
                }
                if (fileMod == null)
                {
                    function.WriteErrMsg("文件不存在!");
                }
                if (upMod.CompID != fileMod.CompID)
                {
                    function.WriteErrMsg("你没有该文档的访问权限!");
                }
                vpath = fileMod.VPath + fileMod.SFileName;
            }
            else if (!string.IsNullOrEmpty(Request["CloudFile"]))
            {
                B_User_Cloud cloudBll = new B_User_Cloud();
                M_User_Cloud cloudMod = cloudBll.SelReturnModel(Request["CloudFile"]);
                if (cloudMod == null)
                {
                    function.WriteErrMsg("云端文件不存在!");
                }
                if (cloudMod.UserID != buser.GetLogin().UserID)
                {
                    function.WriteErrMsg("你无权访问该文件!");
                }
                vpath = cloudMod.VPath + cloudMod.SFileName;
            }
            else
            {
                function.WriteErrMsg("你没有指定文件");
            }
            vpath = vpath.ToLower().Replace("/uploadfiles/", "");
            vpath = "/uploadfiles/" + SafeSC.PathDeal(vpath);
            string ppath  = Server.MapPath(vpath);
            string exName = Path.GetExtension(vpath).ToLower().Replace(".", "");//doc

            if (!File.Exists(function.VToP(vpath)))
            {
                function.WriteErrMsg(Path.GetFileName(Request.QueryString["vpath"]) + "文件不存在!");
            }
            if (!badmin.CheckLogin() && !buser.CheckLogin())
            {
                function.WriteErrMsg("请先登录,再使用该页面!!!");
            }
            else if (SafeSC.FileNameCheck(vpath))
            {
                function.WriteErrMsg("文件名异常,请去除特殊符号,或更换后缀名");
            }
            else if (Path.GetExtension(vpath).Equals(".config"))
            {
                function.WriteErrMsg("为安全考虑,该类型文件不提供预览服务!!");
            }
            /*------------*/
            if (!string.IsNullOrEmpty(Request.QueryString["width"]))
            {
                viewWidth = Convert.ToInt32(Request.QueryString["width"]);
            }
            if (!string.IsNullOrEmpty(Request.QueryString["height"]))
            {
                viewHeight = Convert.ToInt32(Request.QueryString["height"]);
            }
            /*------------------------------------------------------------------*/
            if (WordEx.Contains(exName))//Office类预览
            {
                generalDiv.Visible = true;
                string pdfPath = vpath + ".pdf";
                if (!File.Exists(Server.MapPath(pdfPath)))
                {
                    Document doc = new Document(ppath);
                    doc.Save(Server.MapPath(pdfPath), SaveFormat.Pdf);
                }
                pdfDiv.Visible = true;
                pdfUrl         = VpathToUrl(pdfPath);
                //if (DeviceHelper.GetBrower() == DeviceHelper.Brower.IE)
                //{
                //    function.WriteErrMsg("IE不支持Word预览,请使用Chrome,Edge或其他浏览器");
                //}
            }
            else if (ExcelEx.Contains(exName))
            {
                //generalDiv.Visible = true;
                //string pdfPath = vpath + ".pdf";
                //if (!File.Exists(Server.MapPath(pdfPath)))
                //{
                //    Aspose.Cells.Workbook excel = new Aspose.Cells.Workbook(Server.MapPath(vpath));
                //    excel.Save(Server.MapPath(pdfPath), Aspose.Cells.SaveFormat.Pdf);
                //}
                //pdfDiv.Visible = true;
                //pdfUrl = VpathToUrl(pdfPath);
                function.WriteErrMsg("暂未开放Excel预览,请联系官方技术支持!");
            }
            else if (exName.Equals("pdf"))
            {
                //if (DeviceHelper.GetBrower() == DeviceHelper.Brower.IE)
                //{
                //    function.WriteErrMsg("IE不支持PDF预览,请使用Chrome,Edge或其他浏览器");
                //}
                pdfDiv.Visible = true;
                pdfUrl         = VpathToUrl(vpath);
            }
            else if (ImgEx.Contains(exName))
            {
                imgDiv.Visible = true;
                imgUrl         = vpath;
            }
            else if (exName.Equals("html") || exName.Equals("htm"))
            {
                Server.Transfer(vpath);
            }
            else if (exName.Equals("txt"))
            {
                ViewTxt.Visible = true;
                ViewTxt.Text    = SafeSC.ReadFileStr(vpath);
                ViewTxt.Width   = viewWidth;
                ViewTxt.Height  = viewHeight;
            }
            else if (VideoEx.Contains(exName))
            {
                videoDiv.Visible = true;
                function.Script(this, "PlayVideo();");
            }
            else
            {
                function.WriteErrMsg("暂不支持<span style='color:#0066cc;'>[" + exName + "]</span>格式文件预览,请联系管理员提供支持!!");
            }
        }
Beispiel #12
0
        /// <summary>
        /// 从指定服务器上下载文件,支持断点续传
        /// </summary>
        /// <param name="url">目标Url</param>
        /// <param name="vpath">本地虚拟路径</param>
        /// <param name="begin">开始位置,默认为0</param>
        public void DownFile(string url, string vpath, int begin = 0)
        {
            vpath = SafeSC.PathDeal(vpath);
            if (SafeSC.FileNameCheck(vpath))
            {
                throw new Exception("不支持下载[" + Path.GetFileName(vpath) + "]文件");
            }
            string ppath = function.VToP(vpath);

            //已完成的,1%长度
            int  CompletedLength = 0;
            long percent = 0; string temp = "0";
            long sPosstion = 0;//磁盘现盘文件的长度
            //long count = 0;// count += sPosstion,从指定位置开始写入字节
            FileStream FStream;

            if (File.Exists(ppath))
            {
                FStream   = File.OpenWrite(ppath);           //打开继续写入,并从尾部开始,用于断点续传(如果不需要,则应该删除其)
                sPosstion = FStream.Length;
                FStream.Seek(sPosstion, SeekOrigin.Current); //移动文件流中的当前指针
            }
            else
            {
                string dir = Path.GetDirectoryName(ppath);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                FStream   = new FileStream(ppath, FileMode.Create);
                sPosstion = 0;
            }
            //打开网络连接
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                //if (CompletedLength > 0)
                //    myRequest.AddRange((int)CompletedLength);//设置Range值,即头,从指定位置开始接收文件..
                //向服务器请求,获得服务器的回应数据流
                HttpWebResponse webResponse = (HttpWebResponse)myRequest.GetResponse();
                long            FileLength  = webResponse.ContentLength;//文件大小
                percent = FileLength / 100;
                Stream myStream  = webResponse.GetResponseStream();
                byte[] btContent = new byte[1024];
                //if (count <= 0) count += sPosstion;//
                //开始写入
                int count = 0;
                while ((count = myStream.Read(btContent, 0, 1024)) > 0) //返回读了多少字节,为0表示全部读完
                {
                    FStream.Write(btContent, 0, count);                 //知道有多少个数字节后再写入
                    CompletedLength += count;
                    if (!(CompletedLength / percent).ToString().Equals(temp))
                    {
                        temp = (CompletedLength / percent).ToString();
                        //progStatus = temp;
                    }
                }
                myStream.Close();
            }
            finally
            {
                FStream.Close();
            }
        }
Beispiel #13
0
        //互动模型需要扩展
        public void RestoreByName(string name)
        {
            B_Model      modelBll = new B_Model();
            B_ModelField fieldBll = new B_ModelField();
            B_Pub        pubBll   = new B_Pub();
            string       ppath    = SafeSC.PathDeal(pdir + name);

            if (!File.Exists(ppath))
            {
                function.WriteErrMsg("备份文件[" + name + "]不存在");
            }
            //清空数据
            modelBll.DeleteAll();
            foreach (string tbname in tbnames)
            {
                SqlHelper.ExecuteSql("TRUNCATE TABLE " + tbname);
            }
            SqlHelper.ExecuteSql("TRUNCATE TABLE ZL_CommonModel");
            //开始恢复
            DataSet ds = new DataSet();

            ds.ReadXml(ppath);
            //批量导入部分数据
            SqlHelper.Insert_Bat(ds.Tables["ZL_Node"], SqlHelper.ConnectionString);
            if (ds.Tables["ZL_Pub"] != null)
            {
                SqlHelper.Insert_Bat(ds.Tables["ZL_Pub"], SqlHelper.ConnectionString);
            }
            if (ds.Tables["ZL_Node_ModelTemplate"] != null)
            {
                SqlHelper.Insert_Bat(ds.Tables["ZL_Node_ModelTemplate"], SqlHelper.ConnectionString);
            }
            if (ds.Tables["ZL_UserPromotions"] != null)
            {
                SqlHelper.Insert_Bat(ds.Tables["ZL_UserPromotions"], SqlHelper.ConnectionString);
            }
            if (ds.Tables["ZL_NodeRole"] != null)
            {
                SqlHelper.Insert_Bat(ds.Tables["ZL_NodeRole"], SqlHelper.ConnectionString);
            }
            //恢复模型数据与其对应的表
            DataTable modelDT = ds.Tables["ZL_Model"];
            DataTable fieldDT = ds.Tables["ZL_ModelField"];
            DataTable pubDT   = ds.Tables["ZL_Pub"];

            foreach (DataRow dr in modelDT.Rows)
            {
                M_ModelInfo modelMod = new M_ModelInfo().GetModelFromReader(dr);
                ZoomLa.SQLDAL.DBHelper.Table_Del(modelMod.TableName);
                switch (modelMod.ModelType.ToString())
                {
                case "3":    //用户模型和黄页申请模型
                    modelBll.AddUserModel(modelMod);
                    break;

                case "6":    //店铺申请模型
                    modelBll.AddStoreModel(modelMod);
                    break;

                case "7":    //互动模型
                    if (pubDT == null)
                    {
                        break;
                    }
                    M_Pub pubmodel = new M_Pub();
                    pubmodel.PubName      = modelMod.ModelName;
                    pubmodel.PubTableName = modelMod.TableName;
                    DataRow[] drs = pubDT.Select("PubModelID=" + modelMod.ModelID);
                    pubmodel.PubType = drs.Length > 0 ? DataConvert.CLng(drs[0]["PubType"]) : 0;
                    pubBll.CreateModelInfo(pubmodel);
                    break;

                case "8":    //功能模型
                    modelBll.AddFunModel(modelMod);
                    break;

                default:    //内容模型、商城模型、黄页内容模型、店铺商品模型
                    modelBll.AddModel(modelMod);
                    break;
                }
            }
            //恢复字段
            if (fieldDT != null && fieldDT.Rows.Count > 0)
            {
                fieldDT.DefaultView.RowFilter = "sys_type ='false'";
                foreach (DataRow dr in fieldDT.DefaultView.ToTable().Rows)
                {
                    int modelID = DataConvert.CLng(dr["ModelID"]);
                    if (modelID < 1)
                    {
                        continue;
                    }
                    DataRow[] drs = modelDT.Select("ModelID='" + modelID + "'");
                    //OA不处理,未找到不处理
                    if (drs.Length < 1 || drs[0]["ModelType"].ToString().Equals("12"))
                    {
                        continue;
                    }
                    M_ModelInfo  modelMod = new M_ModelInfo().GetModelFromReader(drs[0]);
                    M_ModelField fieldMod = new M_ModelField().GetModelFromReader(dr);
                    //Pub表会报重复
                    if (fieldBll.IsExists(modelMod.ModelID, fieldMod.FieldName))
                    {
                        continue;
                    }
                    if (DBCenter.DB.Table_Exist(modelMod.TableName)) //互动表可能未创建,忽略
                    {
                        fieldBll.AddModelField(modelMod, fieldMod);
                    }
                }
                SqlHelper.ExecuteSql("TRUNCATE TABLE ZL_ModelField");
                SqlHelper.Insert_Bat(fieldDT, SqlHelper.ConnectionString);
            }
        }
Beispiel #14
0
        public IActionResult UploadFileHandler()
        {
            //HttpRequest Request = context.Request;
            //context.Response.ContentType = "text/plain";
            //context.Request.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            //context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            var file = Request.Form.Files["Filedata"];

            if (file == null)
            {
                file = Request.Form.Files["file"];//接受Uploadify或WebUploader传参,优先Uploadify
            }
            if (file == null || file.Length < 1)
            {
                return(Content(Failed.ToString()));
            }
            if (SafeSC.FileNameCheck(file.FileName))
            {
                throw new Exception("不允许上传该后缀名的文件");
            }
            M_UserInfo mu = buser.GetLogin();

            if (adminMod == null && mu.IsNull)
            {
                throw new Exception("未登录");
            }
            /*-------------------------------------------------------------------------------------------*/
            M_User_Plat upMod = new B_User_Plat().SelReturnModel(mu.UserID);
            string      uploadPath = SiteConfig.SiteOption.UploadDir.TrimEnd('/') + "/", filename = "", ppath = "", result = "0";//上传根目录,文件名,上物理路径,结果
            string      action = GetParam("action"), value = GetParam("value");

            try
            {
                switch (action)
                {
                    #region OA与能力中心
                case "OAattach":    //OA--公文||事务--附件
                                    //uploadPath += "OA/" + mu.UserName + mu.UserID + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                    uploadPath = ZLHelper.GetUploadDir_User(mu, "OA");
                    ppath      = function.VToP(uploadPath);
                    //判断是否有同名文件的存在
                    break;

                case "Blog":    //能力中心--博客
                    uploadPath = B_Plat_Common.GetDirPath(upMod, B_Plat_Common.SaveType.Blog);
                    ppath      = function.VToP(uploadPath);
                    break;

                case "Plat_Doc":    //能力中心--我的文档
                    uploadPath = B_Plat_Common.GetDirPath(upMod, B_Plat_Common.SaveType.Person) + SafeSC.PathDeal(GetParam("Dir"));
                    ppath      = function.VToP(uploadPath);
                    break;

                case "Plat_Doc_Common":    //能力中心--公司文档
                    uploadPath = B_Plat_Common.GetDirPath(upMod, B_Plat_Common.SaveType.Company) + SafeSC.PathDeal(GetParam("Dir"));
                    ppath      = function.VToP(uploadPath);
                    break;

                case "Plat_Task":    //能力中心--任务中心附件
                    int tid = Convert.ToInt32(value);
                    ZoomLa.Model.Plat.M_Plat_Task taskMod = new B_Plat_Task().SelReturnModel(tid);
                    uploadPath = B_Plat_Common.GetDirPath(upMod, B_Plat_Common.SaveType.Plat_Task) + taskMod.TaskName + "/";
                    break;

                case "Plat_Project":    //能力中心--项目
                    int pid = Convert.ToInt32(value);
                    ZoomLa.Model.Plat.M_Plat_Pro proMod = new B_Plat_Pro().SelReturnModel(pid);
                    uploadPath = B_Plat_Common.GetDirPath(upMod, B_Plat_Common.SaveType.Plat_Task) + proMod.Name + "/";
                    break;

                    #endregion
                case "ModelFile":    //组图,多图等
                {
                    int nodeid = Convert.ToInt32(value);
                    //M_Node nodeMod = new B_Node().GetNodeXML(nodeid);
                    string exname = Path.GetExtension(file.FileName).Replace(".", "");
                    //string fpath = nodeMod.NodeDir + "/" + exname + "/" + DateTime.Now.ToString("yyyy/MM/");
                    uploadPath = ZLHelper.GetUploadDir_System("field", "images", "yyyyMMdd");
                    filename   = DateTime.Now.ToString("HHmmss") + function.GetRandomString(6, 2) + "." + exname;
                }
                break;

                case "admin_custom":    //管理员上传,自定义路径
                {
                    if (adminMod == null || adminMod.AdminId < 1)
                    {
                        throw new Exception("管理员未登录");
                    }
                    uploadPath = GetParam("save");       //BannerAdd
                }
                break;

                default:    //通常格式,不需做特殊处理的格式但必须登录
                    if (mu.UserID > 0)
                    {
                        //uploadPath = context.Server.UrlDecode(uploadPath + "User/" + mu.UserName + mu.UserID + "/");
                        uploadPath = ZLHelper.GetUploadDir_User(mu, "User", "", "");
                    }
                    else if (adminMod != null)
                    {
                        //uploadPath = context.Server.UrlDecode(uploadPath + "Admin/" + adminMod.AdminName + adminMod.AdminId + "/");
                        uploadPath = ZLHelper.GetUploadDir_Admin(adminMod, "", "", "yyyyMMdd");
                    }
                    else
                    {
                        //注册等页面用户未登录
                        uploadPath = ZLHelper.GetUploadDir_System("user", "register", DateTime.Now.ToString("yyyyMMdd"));
                    }
                    break;
                }
                string uploadDir = Path.GetDirectoryName(function.VToP(uploadPath));
                if (!Directory.Exists(uploadDir))
                {
                    SafeSC.CreateDir(function.PToV(uploadDir));
                }
                if (action.Equals("Plat_Doc") || action.Equals("Plat_Doc_Common"))
                {
                    #region 能力中心文档
                    M_Plat_File fileMod = new M_Plat_File();
                    B_Plat_File fileBll = new B_Plat_File();
                    fileMod.FileName  = file.FileName;
                    fileMod.SFileName = function.GetRandomString(12) + Path.GetExtension(file.FileName);
                    fileMod.VPath     = uploadPath.Replace("//", "/");
                    fileMod.UserID    = upMod.UserID.ToString();
                    fileMod.CompID    = upMod.CompID;
                    //SafeSC.SaveFile(uploadPath, file, fileMod.SFileName);
                    fileMod.FileSize = new FileInfo(ppath + fileMod.SFileName).Length.ToString();
                    fileBll.Insert(fileMod);
                    #endregion
                }
                else if (action.Equals("Cloud_Doc"))
                {
                    #region 用户中心云盘
                    if (!buser.CheckLogin())
                    {
                        throw new Exception("云盘,用户未登录");
                    }
                    M_User_Cloud cloudMod = new M_User_Cloud();
                    B_User_Cloud cloudBll = new B_User_Cloud();
                    uploadPath         = HttpUtility.UrlDecode(cloudBll.H_GetFolderByFType(GetParam("type"), mu)) + GetParam("value");
                    cloudMod.FileName  = file.FileName;
                    cloudMod.SFileName = function.GetRandomString(12) + Path.GetExtension(file.FileName);
                    cloudMod.VPath     = (uploadPath + "/").Replace("//", "/");
                    cloudMod.UserID    = mu.UserID;
                    cloudMod.FileType  = 1;
                    //result = SafeSC.SaveFile(cloudMod.VPath, file, cloudMod.SFileName);
                    //if (SafeSC.IsImage(cloudMod.SFileName))
                    //{
                    //    string icourl = SiteConfig.SiteOption.UploadDir + "YunPan/" + mu.UserName + mu.UserID + "/ico" + value + "/";
                    //    if (!Directory.Exists(function.VToP(icourl))) { SafeSC.CreateDir(icourl); }
                    //    ImgHelper imghelp = new ImgHelper();
                    //    imghelp.CompressImg(file, 100, icourl + cloudMod.SFileName);
                    //}
                    cloudMod.FileSize = new FileInfo(function.VToP(cloudMod.VPath) + cloudMod.SFileName).Length.ToString();
                    cloudBll.Insert(cloudMod);
                    #endregion
                }
                else
                {
                    //string fname = CreateFName(file.FileName);
                    //if (SafeC.IsImageFile(file.FileName) && file.Length > (5 * 1024 * 1024))//图片超过5M则压缩
                    //{
                    //    result = uploadPath + function.GetRandomString(6) + fname;
                    //    new ImgHelper().CompressImg(file, 5 * 1024, result);
                    //}
                    //else
                    //{
                    result = SafeC.SaveFile(uploadPath, filename, file.OpenReadStream(), (int)file.Length);
                    //}
                    //添加水印
                    //if (WaterModuleConfig.WaterConfig.EnableUserWater)
                    //{
                    //    //未以管理员身份登录,并有会员身份登录记录
                    //    if (adminMod == null && !mu.IsNull)
                    //    {
                    //        Image img = WaterImages.DrawFont(ImgHelper.ReadImgToMS(result), mu.UserName + " " + DateTime.Now.ToString("yyyy/MM/dd"), 9);
                    //        ImgHelper.SaveImage(result, img);
                    //    }
                    //}
                    //else if (DataConverter.CStr(context.Request["IsWater"]).Equals("1"))
                    //{
                    //    //前台主动标识需要使用水印
                    //    result = ImgHelper.AddWater(result);
                    //}
                }
                ZLLog.L(ZLEnum.Log.fileup, new M_Log()
                {
                    UName   = mu.UserName,
                    Source  = Request.RawUrl(),
                    Message = "上传成功|文件名:" + file.FileName + "|" + "保存路径:" + uploadPath
                });
            }
            catch (Exception ex)
            {
                ZLLog.L(ZLEnum.Log.fileup, new M_Log()
                {
                    UName   = mu.UserName,
                    Source  = Request.RawUrl(),
                    Message = "上传失败|文件名:" + file.FileName + "|" + "原因:" + ex.Message
                });
            }
            return(Content(result));
        }
        public M_Blog_Msg FillMsg(string msg, int pid = 0, int rid = 0)
        {
            M_User_Plat upMod = B_User_Plat.GetLogin();
            M_Blog_Msg  model = new M_Blog_Msg();

            model.MsgType = 1;
            model.Status  = 1;
            model.CUser   = upMod.UserID;
            model.CUName  = upMod.TrueName;
            #region 信息内容处理
            msg = Server.HtmlEncode(msg); //避免写入js,后面可插入Html
                                          //------处理@功能
            //@功能
            {
                MatchCollection mc = regHelper.GetValuesBySE(msg, "@", "]");
                int             id = 0;
                string          atuser = "", atgroup = "", name = "";
                string          uTlp = "<a href='javascript:;' onclick='ShowUser({0});'>{1}</a>";
                string          gTlp = "<a href='javascript:;' onclick='ShowGroup({0});'>{1}</a>";
                foreach (Match m in mc)
                {
                    if (string.IsNullOrEmpty(m.Value))
                    {
                        continue;
                    }
                    if (m.Value.Contains("uid:"))
                    {
                        id      = DataConvert.CLng(regHelper.GetValueBySE(m.Value, "uid:", "]", false));
                        name    = regHelper.GetValueBySE(m.Value, "@", @"\[").Replace("[", "");
                        atuser += id + ",";
                        msg     = msg.Replace(m.Value, string.Format(uTlp, id, name));
                    }
                    else if (m.Value.Contains("gid:"))
                    {
                        id       = DataConvert.CLng(regHelper.GetValueBySE(m.Value, "gid:", "]", false));
                        name     = regHelper.GetValueBySE(m.Value, "@", @"\[").Replace("[", "");
                        atgroup += id + ",";
                        msg      = msg.Replace(m.Value, string.Format(gTlp, id, name));
                    }
                    msg = msg.Replace(m.Value, "");
                }
                if (!string.IsNullOrEmpty(atuser) || !string.IsNullOrEmpty(atgroup))
                {
                    atuser += upBll.SelByGIDS(atgroup);
                    if (!string.IsNullOrEmpty(atuser.Replace(",", "")))
                    {
                        model.ATUser = StrHelper.IdsFormat(atuser);
                        //model.ATUser = model.ATUser.Replace("," + upMod.UserID, "");//过滤自己
                        //提示被@人
                        M_Notify notifyMod = new M_Notify();
                        notifyMod.CUName    = upMod.UserName;
                        notifyMod.Title     = "Hi,有人@你了,点击查看详情";
                        notifyMod.Content   = msg.Length > 30 ? msg.Substring(0, 30) : msg;
                        notifyMod.ReceUsers = model.ATUser;
                        B_Notify.NotifyList.Add(notifyMod);
                    }
                }
            }
            #endregion
            model.MsgContent = msg;
            model.pid        = pid;
            model.ReplyID    = rid;
            if (rid > 0)
            {
                M_Blog_Msg msgMod = msgBll.SelReturnModel(model.ReplyID);
                model.ReplyUserID = msgMod.CUser;
                model.ReplyUName  = msgMod.CUName;
            }
            if (!string.IsNullOrEmpty(Request.Form["Attach_Hid"]))//为安全,不允许全路径,必须后台对路径处理
            {
                string     uppath = B_Plat_Common.GetDirPath(B_Plat_Common.SaveType.Blog);
                M_UserInfo bus    = buser.GetLogin();
                string     files  = SafeSC.PathDeal(Request.Form["Attach_Hid"].Trim());
                foreach (string file in files.Split('|'))
                {
                    if (string.IsNullOrEmpty(file))
                    {
                        continue;
                    }
                    model.Attach += uppath + file + "|";
                }
            }
            model.GroupIDS  = Request.Form["GroupIDS_Chk"];//后期需加入检测,避免前台伪造
            model.ColledIDS = "";
            //model.CompID = upMod.CompID;
            return(model);
        }
Beispiel #16
0
        //Html必须编码后再传输,html默认的是将其UrlEncode后传递,服务端再编辑,直接传是不能的
        //public M_Http_Result UploadParam(string url, Dictionary<string, object> postParameters)
        //{
        //    HttpMultipartFormRequest req = new HttpMultipartFormRequest();
        //    //req.config = config;
        //    M_Http_Result result = new M_Http_Result();
        //    result = req.AsyncHttpRequest(url, postParameters, null);
        //    return result;
        //}
        #endregion


        #region 文件下载
        /// <summary>
        /// 从指定服务器上下载文件,支持断点续传
        /// </summary>
        /// <param name="url">目标Url</param>
        /// <param name="vpath">本地虚拟路径</param>
        /// <param name="begin">开始位置,默认为0</param>
        public static void DownFile(string url, string vpath, int begin = 0)
        {
            //尝试除以0,原因:下载的文字过小,占用字节为0
            vpath = SafeSC.PathDeal(vpath);
            if (SafeSC.FileNameCheck(vpath))
            {
                throw new Exception("不支持下载[" + Path.GetFileName(vpath) + "]文件");
            }
            string ppath = function.VToP(vpath);

            //long percent = 0;
            long sPosstion = 0;//磁盘现盘文件的长度
            //long count = 0;// count += sPosstion,从指定位置开始写入字节
            FileStream FStream;

            if (File.Exists(ppath))
            {
                FStream   = File.OpenWrite(ppath);           //打开继续写入,并从尾部开始,用于断点续传(如果不需要,则应该删除其)
                sPosstion = FStream.Length;
                FStream.Seek(sPosstion, SeekOrigin.Current); //移动文件流中的当前指针
            }
            else
            {
                string dir = Path.GetDirectoryName(ppath);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                try { FStream = new FileStream(ppath, FileMode.Create); }
                catch (Exception ex) { throw new Exception(ex.Message + "||" + ppath); }
                sPosstion = 0;
            }
            //打开网络连接
            Stream myStream = null;

            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                //if (CompletedLength > 0)
                //    myRequest.AddRange((int)CompletedLength);//设置Range值,即头,从指定位置开始接收文件..
                //向服务器请求,获得服务器的回应数据流
                HttpWebResponse webResponse = (HttpWebResponse)myRequest.GetResponse();
                //long FileLength = webResponse.ContentLength;//文件大小
                //percent = FileLength / 100;
                myStream = webResponse.GetResponseStream();
                byte[] btContent = new byte[1024];
                //开始写入
                int count = 0;
                while ((count = myStream.Read(btContent, 0, 1024)) > 0) //返回读了多少字节,为0表示全部读完
                {
                    FStream.Write(btContent, 0, count);                 //知道有多少个数字节后再写入
                }
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("基础连接已经关闭"))
                {
                    throw new Exception("DownFile:" + ex.Message + "|" + url);
                }
            }
            finally
            {
                if (myStream != null)
                {
                    myStream.Close();
                }
                if (FStream != null)
                {
                    FStream.Close();
                }
            }
        }