Пример #1
0
        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="fileType"></param>
        /// <returns></returns>
        public ActionResult GetFileList(string fileType)
        {
            string   callback = Request["callback"];
            ListFile listFile = new ListFile();

            if (fileType == "listimage")
            {
                listFile.SearchExtensions = UEditorConfig.GetStringList("imageManagerAllowFiles");
                listFile.PathToList       = UEditorConfig.GetString("imageManagerListPath");
            }
            if (fileType == "listfile")
            {
                listFile.SearchExtensions = UEditorConfig.GetStringList("fileManagerAllowFiles");
                listFile.PathToList       = UEditorConfig.GetString("fileManagerListPath");
            }
            try
            {
                listFile.Start = String.IsNullOrEmpty(Request["start"]) ? 0 : Convert.ToInt32(Request["start"]);
                listFile.Size  = String.IsNullOrEmpty(Request["size"]) ? UEditorConfig.GetInt("imageManagerListSize") : Convert.ToInt32(Request["size"]);
            }
            catch (FormatException)
            {
                listFile.State = ResultState.InvalidParam;
                return(Content(WriteFileResult(callback, listFile), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript"));
            }
            string result       = string.Empty;
            var    buildingList = new List <String>();

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

            return(Content(result, string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript"));
        }
Пример #2
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 不被支持。" }));
            }
        }
Пример #3
0
        public ActionResult UploadFile(string fileType)
        {
            string       callback = Request["callback"];
            UploadResult result   = new UploadResult()
            {
                State = UploadState.Unknown
            };
            UEditorModel uploadConfig = new UEditorModel();

            if (fileType == "uploadimage")
            {
                uploadConfig = new UEditorModel()
                {
                    AllowExtensions = UEditorConfig.GetStringList("imageAllowFiles"),
                    PathFormat      = UEditorConfig.GetString("imagePathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("imageMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("imageFieldName")
                };
            }
            if (fileType == "uploadscrawl")
            {
                uploadConfig = new UEditorModel()
                {
                    AllowExtensions = new string[] { ".png" },
                    PathFormat      = UEditorConfig.GetString("scrawlPathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("scrawlMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("scrawlFieldName"),
                    Base64          = true,
                    Base64Filename  = "scrawl.png"
                };
            }
            if (fileType == "uploadvideo")
            {
                uploadConfig = new UEditorModel()
                {
                    AllowExtensions = UEditorConfig.GetStringList("videoAllowFiles"),
                    PathFormat      = UEditorConfig.GetString("videoPathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("videoMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("videoFieldName")
                };
            }
            if (fileType == "uploadfile")
            {
                uploadConfig = new UEditorModel()
                {
                    AllowExtensions = UEditorConfig.GetStringList("fileAllowFiles"),
                    PathFormat      = UEditorConfig.GetString("filePathFormat"),
                    SizeLimit       = UEditorConfig.GetInt("fileMaxSize"),
                    UploadFieldName = UEditorConfig.GetString("fileFieldName")
                };
            }
            byte[] uploadFileBytes;
            string uploadFileName;

            if (uploadConfig.Base64)
            {
                uploadFileName  = uploadConfig.Base64Filename;
                uploadFileBytes = Convert.FromBase64String(Request[uploadConfig.UploadFieldName]);
            }
            else
            {
                var file = Request.Files[uploadConfig.UploadFieldName];
                uploadFileName = file.FileName;
                var fileExtension = Path.GetExtension(uploadFileName).ToLower();

                if (!uploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension))
                {
                    result.State = UploadState.TypeNotAllow;
                    return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript"));
                }
                if (!(file.ContentLength < uploadConfig.SizeLimit))
                {
                    result.State = UploadState.SizeLimitExceed;
                    return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript"));
                }
                uploadFileBytes = new byte[file.ContentLength];
                try
                {
                    file.InputStream.Read(uploadFileBytes, 0, file.ContentLength);
                }
                catch (Exception)
                {
                    result.State = UploadState.NetworkError;
                    return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript"));
                }
            }
            result.OriginFileName = uploadFileName;

            var savePath  = PathFormatter.Format(uploadFileName, uploadConfig.PathFormat);
            var localPath = Server.MapPath(savePath);

            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(localPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(localPath));
                }
                System.IO.File.WriteAllBytes(localPath, uploadFileBytes);
                result.Url   = savePath;
                result.State = UploadState.Success;
            }
            catch (Exception e)
            {
                result.State        = UploadState.FileAccessError;
                result.ErrorMessage = e.Message;
            }
            return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript"));
        }