Ejemplo n.º 1
0
        /// <summary>
        /// ckeditor 上传图片
        /// </summary>
        /// <returns></returns>
        public async Task <IActionResult> CKUploadImage()
        {
            string callback = Request.Query["CKEditorFuncNum"];//要求返回值
            var    upload   = Request.Form.Files[0];
            //string tpl = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(\"{1}\", \"{0}\", \"{2}\");</script>";
            CKFileUploadError errorJson = new CKFileUploadError();

            if (upload == null)
            {
                errorJson.error.message = "请选择一张图片!";
                return(Json(errorJson));
            }
            //判断是否是图片类型
            List <string> imgtypelist = new List <string> {
                "image/pjpeg", "image/png", "image/x-png", "image/gif", "image/bmp", "image/jpeg"
            };

            if (imgtypelist.FindIndex(x => x == upload.ContentType) == -1)
            {
                errorJson.error.message = "请选择一张图片!";
                return(Json(errorJson));
                //return Content(string.Format(tpl, "", callback, "请上传一张图片!"), "text/html");
            }

            var    data           = Request.Form.Files["upload"];
            string filepath       = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}images{Path.DirectorySeparatorChar}";
            string thumbsFilePath = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}_thumbs{Path.DirectorySeparatorChar}images{Path.DirectorySeparatorChar}";

            //根据附件配置,设置上传图片目录
            string imgPath = DateTime.Now.Year.ToString();//默认按年

            switch (attach.SaveType)
            {
            case 1:    //按月份
                imgPath = $"{DateTime.Now.Year.ToString()}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("MM")}";
                break;

            case 2:
                imgPath = $"{DateTime.Now.Year.ToString()}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("MM")}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("dd")}";
                break;
            }
            filepath       += imgPath;                                                  //存放路径
            thumbsFilePath += imgPath;                                                  //缩略图路径
            string sFileNameNoExt = Utils.GetFileNameWithoutExtension(upload.FileName); //文件名字,不带扩展名
            string sFullExtension = Utils.GetFileExtName(upload.FileName);              //扩展名
            //图片名字
            string imgname = Utils.GetOrderNum() + Utils.GetFileExtName(upload.FileName);

            switch (attach.IsRandomFileName)
            {
            case 0:    //不随机
                imgname = upload.FileName;
                //判断是否存在
                if (System.IO.File.Exists(Path.Combine(filepath, imgname)))
                {
                    imgname = sFileNameNoExt + "(1)" + sFullExtension;
                }
                break;

            case 1:    //随机字符串
                imgname = Utils.GetShortGUId() + sFullExtension;
                break;

            case 2:    //时间
                imgname = Utils.GetOrderNum() + sFullExtension;
                break;
            }
            string fullpath      = Path.Combine(filepath, imgname);       //图片
            string fullThumbPath = Path.Combine(thumbsFilePath, imgname); //缩略图

            try
            {
                //判断路径
                if (!Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }
                //缩略图路径
                if (!Directory.Exists(thumbsFilePath))
                {
                    Directory.CreateDirectory(thumbsFilePath);
                }
                if (data != null)
                {
                    await Task.Run(() =>
                    {
                        using (FileStream fs = new FileStream(fullpath, FileMode.Create))
                        {
                            data.CopyTo(fs);
                        }
                    });

                    //生成缩略图
                    if (attach.IsCreateThum == 1)
                    {
                        ThumbnailHelper.MakeThumbnailImage(fullpath, fullThumbPath, attach.ThumMaxWidth, attach.ThumMaxHeight, ThumbnailHelper.CutMode.Cut);
                    }
                    //添加水印
                    if (attach.IsWaterMark == 1 && !string.IsNullOrEmpty(attach.WaterMarkImg))
                    {
                        string watermarkimg = _env.WebRootPath + attach.WaterMarkImg.Replace("/", Path.DirectorySeparatorChar.ToString());
                        if (System.IO.File.Exists(watermarkimg))
                        {
                            //先复制一张图片出来
                            string copyfullpath = fullpath.Replace(sFullExtension, "_copy" + sFullExtension);
                            System.IO.File.Copy(fullpath, copyfullpath);

                            Image waterpic = new Bitmap(watermarkimg);
                            Image srcPic   = new Bitmap(copyfullpath);
                            if (waterpic.Width < srcPic.Width && waterpic.Height < srcPic.Height)
                            {
                                waterpic.Dispose();
                                //srcPic.Dispose();
                                try
                                {
                                    WatermarkHelper.AddImageSignPic(srcPic, fullpath, watermarkimg, attach.WaterMarkPlace, attach.WaterMarkQty, attach.WaterMarkDiaphaneity);
                                    srcPic.Dispose();
                                    System.IO.File.Delete(copyfullpath);
                                }
                                catch
                                {
                                    if (System.IO.File.Exists(copyfullpath))
                                    {
                                        System.IO.File.Delete(copyfullpath);
                                    }
                                }
                            }
                            else
                            {
                                waterpic.Dispose();
                                srcPic.Dispose();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorJson.error.message = "图片上传失败," + ex.Message + "!";
                return(Json(errorJson));
                //return Content(string.Format(tpl, "", callback, "图片上传失败:" + ex.Message), "text/html");
            }
            dynamic successJson = new
            {
                fileName = imgname,
                uploaded = 1,
                url      = $"/{attach.AttachPatch}/images/{imgPath.Replace("\\", "/")}/" + imgname
            };

            return(Json(successJson));
            //{"fileName":"20180413145904.png","uploaded":1,"url":"\/userfiles\/files\/Public%20Folder\/20180413145904.png"}
            //return Content(string.Format(tpl, $"/{attach.AttachPatch}/images/{imgPath.Replace("\\", "/")}/" + imgname, callback, ""), "text/html");
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> CKUploadFile()
        {
            string callback = Request.Query["CKEditorFuncNum"];//要求返回值
            var    upload   = Request.Form.Files[0];
            //string tpl = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(\"{1}\", \"{0}\", \"{2}\");</script>";
            CKFileUploadError errorJson = new CKFileUploadError();

            if (upload == null)
            {
                errorJson.error.message = "请选择一个文件!";
                return(Json(errorJson));
            }
            //return Content(string.Format(tpl, "", callback, "请选择一个文件!"), "text/html");
            string sFileNameNoExt = Utils.GetFileNameWithoutExtension(upload.FileName); //文件名字,不带扩展名
            string sFullExtension = Utils.GetFileExtName(upload.FileName);              //扩展名

            if (string.IsNullOrEmpty(sFullExtension))
            {
                errorJson.error.message = "错误的文件类型!";
                return(Json(errorJson));
                //return Content(string.Format(tpl, "", callback, $"错误的文件类型!"), "text/html");
            }
            //判断是否是允许文件扩展名
            string        sAllowedExtensions    = _attachsetting.FileAllowedExtensions;
            List <string> listAllowedExtensions = new List <string>();

            string[] arrAllowedExtensions = sAllowedExtensions.Split(new string[] { "," }, StringSplitOptions.None);
            if (arrAllowedExtensions != null && arrAllowedExtensions.Length > 0)
            {
                foreach (var s in arrAllowedExtensions)
                {
                    listAllowedExtensions.Add(s);
                }
            }
            if (listAllowedExtensions.Find(x => x == sFullExtension.ToLower().Replace(".", "")) == null)
            {
                errorJson.error.message = $"{sFullExtension}的文件类型,不允许上传!";
                return(Json(errorJson));
                //return Content(string.Format(tpl, "", callback, $"{sFullExtension}的文件类型,不允许上传!"), "text/html");
            }
            //判断是否是图片,如果是图片,后面需要生成缩略图并可能的话,就加上水印
            bool isImage = false;
            //判断是否是图片类型
            List <string> imgtypelist = new List <string> {
                "image/pjpeg", "image/png", "image/x-png", "image/gif", "image/bmp"
            };

            if (imgtypelist.FindIndex(x => x == upload.ContentType) >= 0)
            {
                isImage = true;
            }
            var    data           = Request.Form.Files["upload"];
            string filepath       = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}";
            string thumbsFilePath = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}_thumbs{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}";
            //根据附件配置,设置上传图片目录
            string imgPath = DateTime.Now.Year.ToString();//默认按年

            switch (attach.SaveType)
            {
            case 1:    //按月份
                imgPath = $"{DateTime.Now.Year.ToString()}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("MM")}";
                break;

            case 2:
                imgPath = $"{DateTime.Now.Year.ToString()}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("MM")}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("dd")}";
                break;
            }
            //文件名字
            string imgname = Utils.GetOrderNum() + Utils.GetFileExtName(upload.FileName);

            switch (attach.IsRandomFileName)
            {
            case 0:    //不随机
                imgname = upload.FileName;
                //判断是否存在
                if (System.IO.File.Exists(Path.Combine(filepath, imgname)))
                {
                    imgname = sFileNameNoExt + "(1)" + sFullExtension;
                }
                break;

            case 1:    //随机字符串
                imgname = Utils.GetShortGUId() + sFullExtension;
                break;

            case 2:    //时间
                imgname = Utils.GetOrderNum() + sFullExtension;
                break;
            }
            string fullpath      = Path.Combine(filepath, imgname);       //图片
            string fullThumbPath = Path.Combine(thumbsFilePath, imgname); //缩略图,可能的话

            try
            {
                //判断路径
                if (!Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }
                //缩略图路径
                if (isImage && !Directory.Exists(thumbsFilePath))
                {
                    Directory.CreateDirectory(thumbsFilePath);
                }
                if (data != null)
                {
                    await Task.Run(() =>
                    {
                        using (FileStream fs = new FileStream(fullpath, FileMode.Create))
                        {
                            data.CopyTo(fs);
                        }
                    });

                    //生成缩略图
                    if (isImage && attach.IsCreateThum == 1)
                    {
                        ThumbnailHelper.MakeThumbnailImage(fullpath, fullThumbPath, attach.ThumMaxWidth, attach.ThumMaxHeight, ThumbnailHelper.CutMode.Cut);
                    }
                    //添加水印
                    if (isImage && attach.IsWaterMark == 1 && !string.IsNullOrEmpty(attach.WaterMarkImg))
                    {
                        string watermarkimg = _env.WebRootPath + attach.WaterMarkImg.Replace("/", Path.DirectorySeparatorChar.ToString());
                        if (System.IO.File.Exists(watermarkimg))
                        {
                            //先复制一张图片出来
                            string copyfullpath = fullpath.Replace(sFullExtension, "_copy" + sFullExtension);
                            System.IO.File.Copy(fullpath, copyfullpath);

                            Image waterpic = new Bitmap(watermarkimg);
                            Image srcPic   = new Bitmap(copyfullpath);
                            if (waterpic.Width < srcPic.Width && waterpic.Height < srcPic.Height)
                            {
                                waterpic.Dispose();
                                //srcPic.Dispose();
                                try
                                {
                                    WatermarkHelper.AddImageSignPic(srcPic, fullpath, watermarkimg, attach.WaterMarkPlace, attach.WaterMarkQty, attach.WaterMarkDiaphaneity);
                                    srcPic.Dispose();
                                    System.IO.File.Delete(copyfullpath);
                                }
                                catch
                                {
                                    if (System.IO.File.Exists(copyfullpath))
                                    {
                                        System.IO.File.Delete(copyfullpath);
                                    }
                                }
                            }
                            else
                            {
                                waterpic.Dispose();
                                srcPic.Dispose();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorJson.error.message = "文件上传失败:" + ex.Message;
                return(Json(errorJson));
                //return Content(string.Format(tpl, "", callback, "文件上传失败:" + ex.Message), "text/html");
            }
            dynamic successJson = new
            {
                fileName = imgname,
                uploaded = 1,
                url      = $"/{attach.AttachPatch}/images/{imgPath.Replace("\\", "/")}/" + imgname
            };

            return(Json(successJson));
            //return Content(string.Format(tpl, $"/{attach.AttachPatch}/fales/{imgPath.Replace("\\", "/")}/" + imgname, callback, ""), "text/html");
        }