在.net core的web项目中使用kindeditor

本项目是一个.net core的mvc项目

1.下载kindeditor 4.1.11 解压后将文件夹置于 wwwroot目录下,如图:

在.net core的web项目中使用kindeditor_第1张图片

2.在HomeController的Index控制器对应的index视图输入一下代码:

@{
    Layout = null;
}



   
    我是管理员首页
    @*首先要引入关键的两个js*@
   
   
    @*创建KindEditor对象*@
   


   

管理从此开始

   

       

           
       

       

   


3.在以上代码中 使用到了KindeditorPicUpload控制的KEUpload用于处理文本编辑器里面的图片上传 

下面是这个控制器代码:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;

namespace Kdeditor.Start.Controllers
{
    public class KEUploadController : Controller
    {
        private IHostingEnvironment hostingEnv;
        public IActionResult Index()
        {
            return View();
        }
        public KEUploadController(IHostingEnvironment env)
        {
            this.hostingEnv = env;
        }
        ///


        /// Kindeditor图片上传
        ///

        /// Kindeditor图片上传自带的命名,不可更改名称
        /// 不可更改名称 这里没有用到dir
        ///
        public IActionResult KindeditorPicUpload(IList imgFile, string dir)
        {
            //http://www.cnblogs.com/fireicesion/p/9490901.html
            //https://www.cnblogs.com/fishpro/p/how_upload_pic_with_kindeditor_for_asp_net_core.html
            //注意 如果是上传到本地这个文件夹子  那么事先必须创建这个文件夹
            PicUploadResponse rspJson = new PicUploadResponse() { error = 0, url = "/upload/" };
            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("."));
                //创建新的文件名 guid+扩展名
                var filename1 = System.Guid.NewGuid().ToString() + extname;
                tempname = filename1;
                var path = hostingEnv.WebRootPath;
                filename = hostingEnv.WebRootPath + $@"\upload\{filename1}";
                size += file.Length;
                using (FileStream fs = System.IO.File.Create(filename))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                    //这里是业务逻辑
                }
            }
            rspJson.error = 0;
            rspJson.url = $@"../../upload/" + tempname;
            return Json(rspJson);
        }
     
    }
    public class PicUploadResponse
    {
        public int error { get; set; }
        public string url { get; set; }
    }

}

注意这个方法由于是.net core的 所以跟.net framework的有很大区别。

这个代码如果在文本编辑器里上传图片 会将图片传入wwwroot目录下的upload目录中

done!

效果如下图:

在.net core的web项目中使用kindeditor_第2张图片

你可能感兴趣的:(模块功能点)