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

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

时间:2024-05-26 14:35:51浏览次数:29  
标签:function CORE ASP string img 示例 var path 上传

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 = "上传失败", });
    }

 

最后的效果图:

 

标签:function,CORE,ASP,string,img,示例,var,path,上传
From: https://www.cnblogs.com/niunan/p/18213620

相关文章

  • ASP.NET Core 中的运行状况检查
    基本运行状况探测对于许多应用,报告应用在处理请求方面的可用性(运行情况)的基本运行状况探测配置足以发现应用的状态。基本配置会注册运行状况检查服务,并调用运行状况检查中间件以通过运行状况响应在URL终结点处进行响应。默认情况下,不会注册任何特定运行状况检查来测试任何......
  • 写入自定义 ASP.NET Core 中间件
    中间件是一种装配到应用管道以处理请求和响应的软件。ASP.NETCore提供了一组丰富的内置中间件组件,但在某些情况下,你可能需要写入自定义中间件。自定义中间件类通常,中间件封装在类中,并且通过扩展方法公开。一、内联中间件(不推荐) 请考虑以下内联中间件,该中间件通过查询字......
  • Aspire 框架预览版
    .NETAspire正式发布:简化.NET云原生开发 合集-.NETAspire(7) 1.Aspire框架预览版发布,使云原生开发和运维更加简单2023-11-162..NETAspirePreview4发布!03-153..NETAspire预览5版本发布04-114..NETASPIRE预览版7发布05-165..NETAspire预览版6发布04-......
  • ASP.NET MVC使用Layui选择多图片上传
    前言多图上传在一些特殊的需求中我们经常会遇到,其实多图上传的原理大家都有各自的见解。对于Layui多图上传和我之前所说的通过js获取文本框中的文件数组遍历提交的原理一样,只不过是Layui中的upload.render方法已经帮我们封装好了,我们只管调用即可,也就是说你选中了几张图片,那么......
  • 解决移植Metasploitable3到VM虚拟机无网络的问题
    第一步导入后不要开机,先在虚拟机设置里面将原有的两个网络适配器移除。第二步接着在选项里面,在客户机操作系统里面,选择MicrosoftWindwos(W),版本选择WindowsServer2008R2x64第三步先打开虚拟机,然后再添加一个网络适配器(没有打开添加不知道行不行,你们可以试试)......
  • Python_DataFrame-的apply方法的应用示例_pandas
    DataFrame拆分-应用-合并split-apply-combineapply()方法是针对某些行或列进行操作的,applymap()方法是针对所有元素进行操作的DataFrame对象,apply函数的语法如下:DataFrame.apply(func,axis=0,raw=False,result_type=None,args=(),**kwds)Series对象,ap......
  • .NET Core中给上传图片的添加水印
    一.安装System.Drawing.Common库工具->NuGet包管理->程序包管理控制台输入命令Install-PackageSystem.Drawing.Common二.代码案例实现usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;usingSystem.Drawing;usingSystem.Drawing.Imaging;usingSy......
  • Django中型项目的目录结构和一个应用创建启动示例
    一个中等Django项目的目录结构包含多个应用、配置文件、静态文件和模板文件等。myproject/├──manage.py#Django项目管理脚本,用于运行服务器、迁移数据库等管理命令├──myproject/#项目配置目录,包含全局配置文件和静态、模板文件│├──__init__.......
  • 2024永久免费破解版CorelDRAW汉化百度云网盘下载
     CorelDRAW®GraphicsSuite2024无疑是一款配备齐全的专业设计工具包,它以其卓越的性能和丰富的功能,为设计师们提供了高效且令人惊艳的矢量插图、布局、照片编辑和排版项目。这款软件套件不仅功能强大,而且价格实惠,用户可以通过订阅的方式获得持续的价值。订阅CorelDRAW®Gr......
  • aspnetcore插件开发dll热加载 二
    这一篇文章应该是个总结。投简历的时候是不是有人问我有没有abp的开发经历,汗颜!在各位大神的尝试及自己的总结下,还是实现了业务和主机服务分离,通过dll动态的加载卸载,控制器动态的删除添加。项目如下: 演示效果: 下面就是代码部分:重点1.IActionDescriptorChangeProvider......