ASP.NET CORE kindeditor在线编辑器示例(上传多图和插入VIDEO标签)

2024年05月26日 更新

以前记录都过时了,ASP.NET ASPX版本的直接看他里面的示例就好,今天把自己弄的上传多图和插入video标签的代码贴上来。。以备以后需要用的时候直接复制粘贴。。。ASP.NET CORE版本,VS2022,

原来里面也有个上传多图和插入视频的。。用的flash来上传多图和插入的embed标签的,现在都过时了,自己另外写界面上传多图和插入video标签

也不知道怎么说。。看代码吧。。

 

@model Niunan.Admin.Model.Diary
@{

    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>新增日记</title>
    <!-- Google Font: Source Sans Pro -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="/dist/css/adminlte.min.css">
    <!-- iCheck for checkboxes and radio inputs -->
    <link rel="stylesheet" href="/plugins/icheck-bootstrap/icheck-bootstrap.min.css">
    <style>
        #moreimg img {
            max-width: 100px;
            margin-left: 10px;
        }

        .oneimg {
            border: 1px solid lightgray;
            padding: 5px;
            margin: 10px;
            text-align: center;
            float: left;
        }
    </style>
</head>
<body>
    <div class="content-wrapper2">
        <section class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1>
                            @if (Model.Id == 0)
                            {
                                @:新增日记
                            }
                            else
                            {
                                @:编辑日记
                            }
                        </h1>
                    </div>

                </div>
            </div><!-- /.container-fluid -->
        </section>
        <section class="content">
            <div class="container-fluid">
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title"></h3>
                    </div>
                    <!-- /.card-header -->
                    <!-- form start -->
                    <form action="/diary/add" method="post">
                        <div class="card-body">
                            <div class="form-group">
                                <label for="Accname">标题</label>

                                @Html.TextBoxFor(a => a.Title, new { @class = "form-control", tabindex = 0, onblur = "checksametitle()",required="required" })
                                <div id="errmsg" style="color:red;"></div>
                            </div>


                            <div class="form-group">
                                <label>内容</label>
                                @Html.TextAreaFor(a => a.Body, new { @class = "form-control", row = 8 })

                            </div>

                            <div class="form-group">
                                <label>上传多图</label>
                                <input type="file" name="fileToUpload" id="fileToUpload" multiple="multiple" onchange="uploadFile();" />
                                <button type="button" onclick="uploadmoreimg()" class="btn btn-sm btn-info">插入</button>
                                <button type="button" class="btn btn-sm btn-danger" onclick="deleteallimg()">全部清除</button>
                                <span id="span_upload_res" style="color:blue;"></span>
                                <div id="moreimg">
                                </div>
                            </div>
                            <div class="form-group">
                                <label>插入视频(video标签)</label>
                        
                                <input type="text" name="videoUrl" id="videoUrl" class="form-control" placeholder="这里输入视频地址,如:http://image.niunan.net/wxblue4.mp4" />
                              
                                <button type="button" onclick="insertVideo()"  class="btn btn-sm btn-info">插入</button>
                               
                            </div>
                        </div>
                        <!-- /.card-body -->
                        @Html.HiddenFor(a => a.Id)
                        @Html.HiddenFor(a => a.Createtime)

                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                @if (Model.Id == 0)
                                {
                                    @:新增
                                }
                                else
                                {
                                    @:修改
                                }
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </section>
    </div>

    <link rel="stylesheet" href="/kindeditor/themes/default/default.css" />
    <link rel="stylesheet" href="/kindeditor/plugins/code/prettify.css" />
    <script src="/plugins/jquery/jquery.js"></script>
    <script src="/kindeditor/kindeditor-all.js"></script>
    <script charset="utf-8" src="/kindeditor/lang/zh-CN.js"></script>
    <script charset="utf-8" src="/kindeditor/plugins/code/prettify.js"></script>
    <script>
        KindEditor.ready(function (K) {
            var editor1 = K.create('#Body', {
                cssPath: '/kindeditor/plugins/code/prettify.css',
                uploadJson: '/Home/KE_Upload',
                height: '500px',
                items: [
                    'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'code', 'cut', 'copy', 'paste',
                    'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
                    'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
                    'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
                    'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
                    'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
                    'insertfile', 'table', 'hr', 'emoticons',   'pagebreak',
                    'anchor', 'link', 'unlink' 
                ], 
                filterMode:false,  //可以任意输入HTML,不受htmlTags限制,为了可以插入video
                afterCreate: function () {
                    var self = this;
                    K.ctrl(document, 13, function () {
                        self.sync();
                        K('form[name=form1]')[0].submit();
                    });
                    K.ctrl(self.edit.doc, 13, function () {
                        self.sync();
                        K('form[name=form1]')[0].submit();
                    });
                }
            });
            prettyPrint();
        });

        //清除所有图片
        function deleteallimg() {
            $('#moreimg').html('')
        }
        //删除一张图片
        function deloneimg(thisobj) {
            $(thisobj).parents(".oneimg").remove();
        }

        //插入上传的多张图片
        function uploadmoreimg() {
            KindEditor.ready(function (K) {
                var h = '';
                $('.oneimg').each(function () {
                    var src = $(this).find("img").attr('src');
                    h += '<img src="' + src + '" />';
                })
                K.insertHtml('#Body', h);
            });
        }

        //插入视频
        function insertVideo() { 
            KindEditor.ready(function (K) {
                var h = '';
                var url = $('#videoUrl').val();
                if (url != '') {
                    h = '<div> <video src="' + url + '" width="600" height="400" controls></video> </div>';
                    K.insertHtml('#Body', h);
                }
                else { 
                    alert('请输入视频地址!');
                }
            });
        }

        //上传多张图片

        function uploadFile() {
            var files = document.getElementById('fileToUpload').files;
            //使用闭包顺序上传
            sequentialAjaxCalls(files);
            // for (var i = 0; i < files.length; i++) {
            //     var file = files[i];
            //     if (!file) { continue; }
            //     console.log("上传图片",file.name);
            //     var fd = new FormData();
            //     fd.append("fileToUpload", file);
            //     var xhr = new XMLHttpRequest();
            //     xhr.addEventListener("load", uploadComplete, false);

            //     xhr.open("POST", "/Home/ImgUpload");
            //     xhr.send(fd);
            // }
        }

        function uploadComplete(evt) {
            console.log(evt.target.responseText)
            var json = JSON.parse(evt.target.responseText);
            $('#moreimg').append('<div class="oneimg"><img src="' + json.data.src + '" /><div><button type="button" class="btn btn-xs btn-danger" onclick="deloneimg(this)">删除</button></div> </div>');
            var x = $('.oneimg').length;
            var sss = "您已上传 " + x + " 张图片!";
            $('#span_upload_res').html(sss);
        }
function sequentialAjaxCalls(files) { function makeCall(index) { if (index >= files.length) { return; } ajaxCall(files[index], function (response) { console.log("服务器端返回",response); // 在这里处理你的响应 var json = JSON.parse(response); $('#moreimg').append('<div class="oneimg"><img src="' + json.data.src + '" /><div><button type="button" class="btn btn-xs btn-danger" onclick="deloneimg(this)">删除</button></div> </div>'); var x = $('.oneimg').length; var sss = "您已上传 " + x + " 张图片!"; $('#span_upload_res').html(sss); makeCall(index + 1); // 递归调用下一个AJAX请求 }); } makeCall(0); // 从第一个开始 } function ajaxCall(file, callback) { var fd = new FormData(); fd.append("fileToUpload", file); var xhr = new XMLHttpRequest(); xhr.open("POST", "/Home/ImgUpload"); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { callback(xhr.responseText); } }; xhr.send(fd); } //上传多张图片end //检测标题同名 function checksametitle() { var title = $('#Title').val() var url = "/diary/SameTitle?title=" + title + "&t=" + new Date().getTime(); $.ajax({ async: false, type: "GET", url: url, success: function (data) { if (data.code == 1) { $('#errmsg').html(data.msg); } else { } } }) } </script> </body> </html>

后台上传图片的代码:

    /// <summary>
    /// kindeditor在线编辑器的上传
    /// </summary>
    /// <returns></returns>
    public IActionResult KE_Upload()
    {


        //定义允许上传的文件扩展名
        Hashtable extTable = new Hashtable();
        extTable.Add("image", "gif,jpg,jpeg,png,bmp");
        extTable.Add("flash", "swf,flv");
        extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        //最大文件大小
        int maxSize = 2000000;

        var imgFile = Request.Form.Files["imgFile"];

        if (imgFile == null)
        {
            return Content(showError("请选择文件。"));
        }

        String dirPath = hostingEnv.WebRootPath;
        if (!Directory.Exists(dirPath))
        {
            showError("上传目录不存在。");
        }


        String fileName = imgFile.FileName;
        String fileExt = Path.GetExtension(fileName).ToLower();

        if (imgFile.Length > maxSize)
        {
            showError("上传文件大小超过限制。");
        }

        if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable["image"]).Split(','), fileExt.Substring(1).ToLower()) == -1)
        {
            showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable["image"]) + "格式。");
        }

        //创建文件夹
        string dir = DateTime.Now.ToString("yyyyMMdd");
        //完整物理路径
        string wuli_path = hostingEnv.WebRootPath + $"{Path.DirectorySeparatorChar}upload{Path.DirectorySeparatorChar}to7niu{Path.DirectorySeparatorChar}";
        if (!System.IO.Directory.Exists(wuli_path))
        {
            System.IO.Directory.CreateDirectory(wuli_path);
        }

        string nohouzui = "niunannet_" + DateTime.Now.ToString("yyyyMMdd") + "_" + Guid.NewGuid().ToString().Substring(0, 6);
        String newFileName = nohouzui + fileExt;

        String filePath = dirPath + newFileName;

        using (FileStream fs = System.IO.File.Create(wuli_path + newFileName))
        {
            imgFile.CopyTo(fs);
            fs.Flush();
            fs.Close();
        }

        String fileUrl = $"/upload/to7niu/" + newFileName;

        #region 生成宽900的图片,小于宽900的则不生成
        int img_w = 0;
        int img_h = 0;
        Tool.GetImgWH(wuli_path + newFileName, out img_w, out img_h);

        string filename_upload = "";
        string tpath = "";
        if (img_w <= 900)
        {
            filename_upload = newFileName;
            tpath = wuli_path + newFileName;
        }
        else
        {
            filename_upload = nohouzui + "_w900" + fileExt;
            tpath = wuli_path + filename_upload;
            Tool.ZoomImage(wuli_path + newFileName, tpath, 900, "width");
            try
            {
                System.IO.File.Delete(wuli_path + newFileName);
                log.Info($"删除本地文件成功:" + wuli_path + newFileName);
            }
            catch (Exception ex)
            {
                log.Error($"删除本地文件失败:" + ex.Message);
            }
        }
        #endregion

        #region 传到七牛云上
        string AccessKey = "WB66666T_20zbdk2O";
        string SecretKey = "cJRT2FA888888cRNJClNnu3x27nz3D";
        string Bucket = "niunan-net";
        Mac mac = new Mac(AccessKey, SecretKey);
        PutPolicy putPolicy = new PutPolicy();
        putPolicy.Scope = Bucket;
        putPolicy.SetExpires(3600);
        string jstr = putPolicy.ToJsonString();
        string token = Auth.CreateUploadToken(mac, jstr);
        Config config = new Config();
        config.Zone = Zone.ZONE_CN_South;
        config.UseHttps = false;
        config.UseCdnDomains = true;
        FormUploader fu = new FormUploader(config);
        Stream s = new System.IO.FileInfo(tpath).OpenRead();
        var result = fu.UploadStream(s, filename_upload, token, null);
        s.Dispose();
        s.Close();
       log.Info($"上传图片到七牛云,文件名【{filename_upload}】,上传结果【{result.ToString()}】");

        try
        {
            System.IO.File.Delete(tpath); 
            log.Info($"删除本地文件成功:"+tpath);
        }
        catch (Exception ex)
        {
            log.Error($"删除本地文件失败:" + ex.Message);
        }
        #endregion

        Hashtable hash = new Hashtable();
        hash["error"] = 0;
        hash["url"] = "http://image.niunan.net/" + filename_upload;// fileUrl;
        return Content(Newtonsoft.Json.JsonConvert.SerializeObject(hash));

    }

    private string showError(string message)
    {
        Hashtable hash = new Hashtable();
        hash["error"] = 1;
        hash["message"] = message;
        string str = Newtonsoft.Json.JsonConvert.SerializeObject(hash);
        return str;
    }

    [HttpPost]
    public IActionResult ImgUpload()
    {
        var imgFile = Request.Form.Files[0];
        if (imgFile != null && !string.IsNullOrEmpty(imgFile.FileName))
        {
            long size = 0;
            var filename = ContentDispositionHeaderValue
                            .Parse(imgFile.ContentDisposition)
                            .FileName
                            .Trim().Value;
            var fileExt = filename.Substring(filename.LastIndexOf('.'), filename.Length - filename.LastIndexOf('.')); //扩展名,如.jpg

            fileExt = fileExt.Replace("\"", "");

            #region 判断后缀
            if (!fileExt.ToLower().Contains("jpg") && !fileExt.ToLower().Contains("png") && !fileExt.ToLower().Contains("gif") && !fileExt.ToLower().Contains("jpeg"))
            {
                return Json(new { code = 1, msg = "只允许上传jpg,png,gif,jpeg格式的图片.", });
            }
            #endregion

            #region 判断大小
            long mb = imgFile.Length / 1024 / 1024; // MB
            if (mb > 20)
            {
                return Json(new { code = 1, msg = "只允许上传小于 20MB 的图片.", });
            }
            #endregion

            // string nohouzui = "niunannet_" + DateTime.Now.ToString("yyyyMMdd") + "_" + System.Guid.NewGuid().ToString().Substring(0, 6);
            string nohouzui = filename;
            String newFileName = nohouzui + fileExt;


            var path = hostingEnv.WebRootPath; //网站静态文件目录  wwwroot
            string dir = DateTime.Now.ToString("yyyyMMdd");
            //完整物理路径
            string wuli_path = path + $"{Path.DirectorySeparatorChar}upload{Path.DirectorySeparatorChar}to7niu{Path.DirectorySeparatorChar}";
            if (!System.IO.Directory.Exists(wuli_path))
            {
                System.IO.Directory.CreateDirectory(wuli_path);
            }
            filename = wuli_path + newFileName;
            size += imgFile.Length;
            using (FileStream fs = System.IO.File.Create(filename))
            {
                imgFile.CopyTo(fs);
                fs.Flush();
            }

            #region 生成宽900的图片,小于宽900的则不生成
            int img_w = 0;
            int img_h = 0;
            Tool.GetImgWH(wuli_path + newFileName, out img_w, out img_h);

            string filename_upload = "";
            string tpath = "";
            if (img_w <= 900)
            {
                filename_upload = newFileName;
                tpath = wuli_path + newFileName;
            }
            else
            {
                filename_upload = nohouzui + "_w900" + fileExt;
                tpath = wuli_path + filename_upload;
                Tool.ZoomImage(wuli_path + newFileName, tpath, 900, "width");
                try
                {
                    System.IO.File.Delete(wuli_path + newFileName);
                    log.Info($"删除本地文件成功:" + wuli_path + newFileName);
                }
                catch (Exception ex)
                {
                    log.Error($"删除本地文件失败:" + ex.Message);
                }
            }
            #endregion
            #region 传到七牛云上
            string AccessKey = "WB-23oGb33333tMRSZ45kvT_20zbdk2O";
            string SecretKey = "cJR55555vVJDhPXTicRNJClNnu3x27nz3D";
            string Bucket = "niunan-net";
            Mac mac = new Mac(AccessKey, SecretKey);
            PutPolicy putPolicy = new PutPolicy();
            putPolicy.Scope = Bucket;
            putPolicy.SetExpires(3600);
            string jstr = putPolicy.ToJsonString();
            string token = Auth.CreateUploadToken(mac, jstr);
            Config config = new Config();
            config.Zone = Zone.ZONE_CN_South;
            config.UseHttps = false;
            config.UseCdnDomains = true;
            FormUploader fu = new FormUploader(config);
            Stream s = new System.IO.FileInfo(tpath).OpenRead();
            var result = fu.UploadStream(s, filename_upload, token, null);
            s.Dispose();
            s.Close();
            log.Info($"上传图片到七牛云,文件名【{filename_upload}】,上传结果【{result.ToString()}】");

            try
            {
                System.IO.File.Delete(tpath); 
                log.Info($"删除本地文件成功:" + tpath);
            }
            catch (Exception ex)
            {
                log.Error($"删除本地文件失败:" + ex.Message);
            }
            string endfilepath = "http://image.niunan.net/" + filename_upload;
            #endregion

            return Json(new { code = 0, msg = "上传成功", data = new { src = endfilepath, title = filename_upload } });
        }
        return Json(new { code = 1, msg = "上传失败", });
    }

 

最后的效果图:

 

posted @ 2024-05-26 14:18  牛腩  阅读(140)  评论(0编辑  收藏  举报