网站换皮肤了
asp.net core 2.0 Kindeditor富文本编辑器
时间:2018-05-14 12:45 浏览:1030

摘要

none

后台接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System.Net.Http.Headers;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace MyBlog.Controllers
{
    public class KindeditorController : Controller
    {
        private IHostingEnvironment hostingEnv;
        public KindeditorController(IHostingEnvironment env)
        {
            hostingEnv = env;
        }
        /// <summary>
        /// Kindeditor图片上传
        /// </summary>
        /// <param name="imgFile">Kindeditor图片上传自带的命名,不可更改名称</param>
        /// <param name="dir">不可更改名称 这里没有用到dir</param>
        /// <returns></returns>
        public IActionResult Upload(IList<IFormFile> imgFile, string dir)
        {
            string uploadPath = $@"/upload/{dir}/" + DateTime.Now.ToString("d");
            PicUploadResponse rspJson = new PicUploadResponse() { Error = 0, Url = uploadPath };
            long size = 0;
            string tempname = "";
            foreach (var file in imgFile)
            {
                var filename = ContentDispositionHeaderValue
                                .Parse(file.ContentDisposition)
                                .FileName
                                .Trim('"');
                var extname = filename.Substring(filename.LastIndexOf("."), filename.Length - filename.LastIndexOf("."));
                var filename1 = Guid.NewGuid().ToString() + extname;
                tempname = filename1;
                var path = hostingEnv.WebRootPath + uploadPath;
                filename = path + $@"/{filename1}";
                size += file.Length;
                if (!Directory.Exists(path))//判断文件夹是否存在 
                {
                    Directory.CreateDirectory(path);//不存在则创建文件夹 
                }
                using (FileStream fs = System.IO.File.Create(filename))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                    //这里是业务逻辑
                }
            }
            rspJson.Error = 0;
            rspJson.Url = $@"../..{uploadPath}/" + tempname;
            return Json(rspJson);
        }
        public IActionResult ProcessRequest(string dir, string path, string order)
        {
            string uploadPath, rootPath, rootUrl;
            if (path == null)
            {
                uploadPath = $@"/upload/{dir}/";
                //根目录路径,相对路径
                rootPath = hostingEnv.WebRootPath + uploadPath;
                //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
                rootUrl = uploadPath;
            }
            else
            {
                uploadPath = path;
                rootPath = hostingEnv.WebRootPath + path;
                rootUrl = path;
            }
            //图片扩展名
            String fileTypes = "gif,jpg,jpeg,png,bmp";
            //排序形式,name or size or type
            order = String.IsNullOrEmpty(order) ? "" : order.ToLower();
            if (!Directory.Exists(rootPath))//判断文件夹是否存在 
            {
                Directory.CreateDirectory(rootPath);//不存在则创建文件夹 
            }
            //遍历目录取得文件信息
            string[] dirList = Directory.GetDirectories(rootPath);
            string[] fileList = Directory.GetFiles(rootPath);
            switch (order)
            {
                case "size":
                    Array.Sort(dirList, new NameSorter());
                    Array.Sort(fileList, new SizeSorter());
                    break;
                case "type":
                    Array.Sort(dirList, new NameSorter());
                    Array.Sort(fileList, new TypeSorter());
                    break;
                case "name":
                default:
                    Array.Sort(dirList, new NameSorter());
                    Array.Sort(fileList, new NameSorter());
                    break;
            }
            Hashtable result = new Hashtable
            {
                ["moveup_dir_path"] = uploadPath,
                ["current_dir_path"] = uploadPath,
                ["current_url"] = rootUrl,
                ["total_count"] = dirList.Length + fileList.Length
            };
            List<Hashtable> dirFileList = new List<Hashtable>();
            result["file_list"] = dirFileList;
            for (int i = 0; i < dirList.Length; i++)
            {
                DirectoryInfo dir_i = new DirectoryInfo(dirList[i]);
                Hashtable hash = new Hashtable
                {
                    ["is_dir"] = true,
                    ["has_file"] = (dir_i.GetFileSystemInfos().Length > 0),
                    ["filesize"] = 0,
                    ["is_photo"] = false,
                    ["filetype"] = "",
                    ["filename"] = dir_i.Name,
                    ["datetime"] = dir_i.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
                };
                dirFileList.Add(hash);
            }
            for (int i = 0; i < fileList.Length; i++)
            {
                FileInfo file = new FileInfo(fileList[i]);
                Hashtable hash = new Hashtable
                {
                    ["is_dir"] = false,
                    ["has_file"] = false,
                    ["filesize"] = file.Length,
                    ["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0),
                    ["filetype"] = file.Extension.Substring(1),
                    ["filename"] = file.Name,
                    ["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
                };
                dirFileList.Add(hash);
            }
            return Json(result);
        }
        public class NameSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());
                return xInfo.FullName.CompareTo(yInfo.FullName);
            }
        }
        public class SizeSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());
                return xInfo.Length.CompareTo(yInfo.Length);
            }
        }
        public class TypeSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());
                return xInfo.Extension.CompareTo(yInfo.Extension);
            }
        }
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

    }
    public class PicUploadResponse
    {
        public int Error { get; set; }
        public string Url { get; set; }
    }
}

  前端调用

    <link rel="stylesheet" href="~/lib/kindeditor/themes/default/default.css" />
    <link rel="stylesheet" href="~/lib/kindeditor/plugins/code/prettify.css" />
    <script src="~/lib/kindeditor/plugins/code/prettify.js"></script>
    <script src="~/lib/kindeditor/kindeditor-all-min.js"></script>
    <script src="~/lib/kindeditor/lang/zh-CN.js"></script>
    <script type="text/javascript">
        $(function () {
            //实例化编辑器
            //建议使用工厂方法getEditor创建和引用编辑器实例,如果在某个闭包下引用该编辑器,直接调用UE.getEditor('editor')就能拿到相关的实例
            KindEditor.ready(function (K) {
                window.editor = K.create('#contents', {
                    width: '100%',
                    height: '500px',
                    uploadJson: '/Kindeditor/Upload',
                    fileManagerJson: '/Kindeditor/ProcessRequest',
                    allowFileManager: true,
                    afterBlur: function () { this.sync(); }
                });
            });
            prettyPrint();
     });
 
        function validate(){
            var title = $("#title").val();
            content=  $("#contents").val(); 
            console.log(title);
            console.log(content);
            if(content == ""){
                alert("内容不能为空")
                return false;  
            }  
                return true;  
        } 
    </script>

                 



如果这篇文章对你有所帮助,可以通过下边的“打赏”功能进行小额的打赏。

本网站部分内容来源于互联网,如有侵犯版权请来信告知,我们将立即处理。


来说两句吧