Ejemplo n.º 1
0
        /// <summary>
        ///     us the editor.
        /// </summary>
        /// <param name="callback">The callback.</param>
        /// <param name="action">The action.</param>
        public IActionResult UEditor([FromQuery] string callback, [FromQuery] string action)
        {
            if (!Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
            {
                Response.Headers.Add("Access-Control-Allow-Origin", "*");
            }

            switch (action)
            {
            case "config":
                if (!callback.IsNullOrEmpty())
                {
                    var items = UEditorConfig.Items;

                    items["imageUrlPrefix"] =
                        Request.IsHttps ? $"https://{Request.Host}/" : $"http://{Request.Host}/";
                    return(new ContentResult {
                        Content = $"{callback}({items})"
                    });
                }

                return(WriteJson(callback, UEditorConfig.Items));

            case "uploadimage":
                var config = new UploadConfig {
                    AllowExtensions = UEditorConfig.GetStringList("imageAllowFiles"),
                    PathFormat      = UEditorConfig.GetString("imagePathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("imageMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("imageFieldName")
                };
                return(UploadFile(callback, config));

            case "uploadscrawl":
                config = new UploadConfig {
                    AllowExtensions = new[] { ".png" },
                    PathFormat      = UEditorConfig.GetString("scrawlPathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("scrawlMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("scrawlFieldName"),
                    Base64          = true,
                    Base64Filename  = "scrawl.png"
                };
                return(UploadFile(callback, config));

            case "uploadvideo":
                config = new UploadConfig {
                    AllowExtensions = UEditorConfig.GetStringList("videoAllowFiles"),
                    PathFormat      = UEditorConfig.GetString("videoPathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("videoMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("videoFieldName")
                };
                return(UploadFile(callback, config));

            case "uploadfile":
                config = new UploadConfig {
                    AllowExtensions = UEditorConfig.GetStringList("fileAllowFiles"),
                    PathFormat      = UEditorConfig.GetString("filePathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("fileMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("fileFieldName")
                };
                return(UploadFile(callback, config));

            case "listimage":
                try {
                    Start = string.IsNullOrEmpty(HttpContext.Request.Query["start"])
                            ? 0
                            : Convert.ToInt32(HttpContext.Request.Query["start"]);
                    Size = Convert.ToInt32(HttpContext.Request.Query["size"]);
                } catch (FormatException) {
                    State = ResultState.InvalidParam;
                    WriteJson(callback, new { });
                }

                try {
                    var localPath = _hostEnvironment.ContentRootPath + "/upload/UEditor/image";
                    buildingList.AddRange(Directory.GetFiles(localPath, "*", SearchOption.AllDirectories)
                                          .Where(x => SearchExtensions.Contains(Path.GetExtension(x).ToLower()))
                                          .Select(x => PathToList + x.Substring(localPath.Length).Replace("\\", "/")));
                    Total    = buildingList.Count;
                    FileList = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();
                } catch (UnauthorizedAccessException) {
                    State = ResultState.AuthorizError;
                } catch (DirectoryNotFoundException) {
                    State = ResultState.PathNotFound;
                } catch (IOException) {
                    State = ResultState.IOError;
                }

                return(WriteJson(callback, new {
                    state = GetStateString(),
                    list = FileList?.Select(x => new { url = x }),
                    start = Start,
                    size = Size,
                    total = Total
                }));

            case "listfile":
                try {
                    Start = string.IsNullOrEmpty(HttpContext.Request.Query["start"])
                            ? 0
                            : Convert.ToInt32(HttpContext.Request.Query["start"]);
                    Size = Convert.ToInt32(HttpContext.Request.Query["size"]);
                } catch (FormatException) {
                    State = ResultState.InvalidParam;
                    WriteJson(callback, new { });
                }

                try {
                    var localPath = _hostEnvironment.ContentRootPath + "/upload/UEditor/file";
                    buildingList.AddRange(Directory.GetFiles(localPath, "*", SearchOption.AllDirectories)
                                          .Where(x => SearchExtensions.Contains(Path.GetExtension(x).ToLower()))
                                          .Select(x => PathToList + x.Substring(localPath.Length).Replace("\\", "/")));
                    Total    = buildingList.Count;
                    FileList = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();
                } catch (UnauthorizedAccessException) {
                    State = ResultState.AuthorizError;
                } catch (DirectoryNotFoundException) {
                    State = ResultState.PathNotFound;
                } catch (IOException) {
                    State = ResultState.IOError;
                }

                return(WriteJson(callback, new {
                    state = GetStateString(),
                    list = FileList?.Select(x => new { url = x }),
                    start = Start,
                    size = Size,
                    total = Total
                }));

            case "catchimage":
                StringValues sources;
                Request.Form.TryGetValue("source[]", out sources);
                if (sources.Count == 0)
                {
                    return(WriteJson(callback, new { state = "参数错误:没有指定抓取源" }));
                }

                var Crawlers = sources.Select(x => new Crawler(x).Fetch(_hostEnvironment)).ToArray();
                return(WriteJson(callback, new {
                    state = "SUCCESS",
                    list = Crawlers.Select(x => new {
                        state = x.State,
                        source = x.SourceUrl,
                        url = x.ServerUrl
                    })
                }));

            default:
                return(WriteJson(callback, new { state = "action 参数为空或者 action 不被支持。" }));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Checks the type of the file.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <param name="config">The configuration.</param>
        private bool CheckFileType(string filename, UploadConfig config)
        {
            var fileExtension = Path.GetExtension(filename).ToLower();

            return(config.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension));
        }
Ejemplo n.º 3
0
 /// <summary>
 ///     Checks the size of the file.
 /// </summary>
 /// <param name="size">The size.</param>
 /// <param name="config">The configuration.</param>
 private bool CheckFileSize(int size, UploadConfig config)
 {
     return(size < config.SizeLimit);
 }
Ejemplo n.º 4
0
        /// <summary>
        ///     Uploads the file.
        /// </summary>
        /// <param name="callback">The callback.</param>
        /// <param name="config">The configuration.</param>
        private IActionResult UploadFile(string callback, UploadConfig config)
        {
            config.PathFormat = "wwwroot/" + config.PathFormat.Replace("upload", "uploads");
            var localPath = string.Empty;

            byte[] uploadFileBytes = null;
            string uploadFileName  = null;

            if (config.Base64)
            {
                uploadFileName  = config.Base64Filename;
                uploadFileBytes = Convert.FromBase64String(Request.Query[config.UploadFieldName]);
            }
            else
            {
                var file = Request.Form.Files[config.UploadFieldName];
                uploadFileName = file.FileName;

                if (!CheckFileType(uploadFileName, config))
                {
                    Result.State = UploadState.TypeNotAllow;
                    return(WriteJson(callback, new {
                        state = GetStateMessage(Result.State),
                        url = Result.Url,
                        title = Result.OriginFileName,
                        original = Result.OriginFileName,
                        error = Result.ErrorMessage
                    }));
                }

                if (!CheckFileSize((int)file.Length, config))
                {
                    Result.State = UploadState.SizeLimitExceed;
                    return(WriteJson(callback, new {
                        state = GetStateMessage(Result.State),
                        url = Result.Url,
                        title = Result.OriginFileName,
                        original = Result.OriginFileName,
                        error = Result.ErrorMessage
                    }));
                }

                uploadFileBytes = new byte[file.Length];
                try {
                    file.OpenReadStream().Read(uploadFileBytes, 0, (int)file.Length);
                } catch (Exception) {
                    Result.State = UploadState.NetworkError;
                    return(WriteJson(callback, new {
                        state = GetStateMessage(Result.State),
                        url = Result.Url,
                        title = Result.OriginFileName,
                        original = Result.OriginFileName,
                        error = Result.ErrorMessage
                    }));
                }
            }

            Result.OriginFileName = uploadFileName;
            var savePath = PathFormatter.Format(uploadFileName, config.PathFormat);

            localPath = _hostEnvironment.ContentRootPath + "/" + savePath;
            try {
                if (!Directory.Exists(Path.GetDirectoryName(localPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(localPath));
                }

                System.IO.File.WriteAllBytes(localPath, uploadFileBytes);
                var extension = Path.GetExtension(uploadFileName).ToLower();
                if (extension == ".jpg" ||
                    extension == ".png" ||
                    extension == ".jpeg" ||
                    extension == ".gif" ||
                    extension == ".bmp")
                {
                    var iSource = Image.FromFile(localPath);
                    if (iSource.PhysicalDimension.Width > 1024)
                    {
                        int dHeight = 64, dWidth = 64;
                        var rate = iSource.Width * 1.00 / iSource.Height;
                        if (rate <= 1)
                        {
                            dHeight = 1024;
                            dWidth  = (int)(rate * 1024);
                        }
                        else
                        {
                            dWidth  = 1024;
                            dHeight = (int)(1024 / rate);
                        }

                        var tFormat = iSource.RawFormat;
                        int sW = dWidth, sH = dHeight;
                        var ob = new Bitmap(dWidth, dHeight);
                        var g  = Graphics.FromImage(ob);
                        g.Clear(Color.WhiteSmoke);
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.SmoothingMode      = SmoothingMode.HighQuality;
                        g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0,
                                    iSource.Width, iSource.Height, GraphicsUnit.Pixel);
                        g.Dispose();
                        iSource.Dispose();
                        //以下代码为保存图片时,设置压缩质量
                        var ep = new EncoderParameters();
                        var qy = new long[1];
                        qy[0] = 90; //设置压缩的比例1-100
                        var eParam = new EncoderParameter(Encoder.Quality, qy);
                        ep.Param[0] = eParam;
                        try {
                            var            arrayICI    = ImageCodecInfo.GetImageEncoders();
                            ImageCodecInfo jpegICIinfo = null;
                            for (var x = 0; x < arrayICI.Length; x++)
                            {
                                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                                {
                                    jpegICIinfo = arrayICI[x];
                                    break;
                                }
                            }

                            if (System.IO.File.Exists(localPath))
                            {
                                System.IO.File.Delete(localPath);
                            }

                            if (jpegICIinfo != null)
                            {
                                ob.Save(localPath, jpegICIinfo, ep); //dFile是压缩后的新路径
                            }
                            else
                            {
                                ob.Save(localPath, tFormat);
                            }
                        } catch (Exception ex) {
                            Console.Write(ex.Message);
                        } finally {
                            iSource.Dispose();
                            ob.Dispose();
                        }
                    }
                }

                Result.Url   = savePath;
                Result.State = UploadState.Success;
            } catch (Exception e) {
                Result.State        = UploadState.FileAccessError;
                Result.ErrorMessage = e.Message;
            }

            return(WriteJson(callback, new {
                state = GetStateMessage(Result.State),
                url = Result.Url,
                title = Result.OriginFileName,
                original = Result.OriginFileName,
                error = Result.ErrorMessage
            }));
        }