Tinymce 文本编辑器

一、前端

 <%-- 编辑器开始--%>
    <script src="../../../Scripts/jquery-1.10.2.min.js"></script>
    <script src="../../Content/tinymce/tinymce.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            tinymce.init({
                selector: "textarea#content",
                //auto_focus: "content",
                language: "zh_CN",
                theme: "silver",
                //引入插件
                plugins: 'advlist code searchreplace autolink link image imagetools lists charmap print preview autoresize table charmap wordcount', 
                //工具栏配置
                toolbar: ['code print removeformat| undo redo | fontselect fontsizeselect forecolor backcolor ',
                    'alignleft aligncenter alignright bold italic bullist numlist indent outdent | blockquote link image wordcount|rotateleft|preview'
                ],
                //覆盖默认上传图片处理事件
                images_upload_handler: function (blobInfo, success, failure) {
                    var xhr, formData;

                    xhr = new XMLHttpRequest();
                    xhr.withCredentials = false;
                    xhr.open('POST', '/Common/UpLoadImg');

                    xhr.onload = function () {
                        var json;
                        if (xhr.status < 200 || xhr.status >= 300) {
                            failure('HTTP Error: ' + xhr.status);
                            return;
                        }
                        json = JSON.parse(xhr.responseText);
                        if (!json.success) {
                            failure('Invalid JSON: ' + xhr.responseText);
                            return;
                        }
                        success(json.response);
                    };
                    formData = new FormData();
                    formData.append('formFile', blobInfo.blob());

                    xhr.send(formData);
                },
                file_picker_types: 'file', // 指定允许上传的类型
                // 文件上传
                file_picker_callback: function (callback, value, meta) {
                    // 要先模拟出一个input用于上传本地文件
                    var input = document.createElement('input');
                    input.setAttribute('type', 'file');
                    // 你可以给input加accept属性来限制上传的文件类型
                    // 例如:input.setAttribute('accept', '.jpg,.png')
                    input.setAttribute('accept', '.doc,.docx,.ppt,.pptx,.pdf,.xls,.xlsx,.txt,.zip,.rar,.7z');
                    input.click();
                    input.onchange = function () {
                        var file = this.files[0];

                        var xhr, formData;
                        xhr = new XMLHttpRequest();
                        xhr.withCredentials = false;
                        xhr.open('POST', '/Common/UpLoadFile');
                        xhr.onload = function () {
                            var json;
                            if (xhr.status !== 200) {
                                this.$message.error('HTTP Error: ' + xhr.status);
                                return
                            }
                            json = JSON.parse(xhr.responseText);
                            if (!json.success) {
                                failure('Invalid JSON: ' + xhr.responseText);
                                return;
                            }
                            callback(json.response);
                        }
                        formData = new FormData();
                        formData.append('formFile', file, file.name);
                        xhr.send(formData);
                    }
                },
                //TinyMCE 会将所有的 font 元素转换成 span 元素
                convert_fonts_to_spans: true,
                //换行符会被转换成 br 元素
                convert_newlines_to_brs: false,
                //在换行处 TinyMCE 会用 BR 元素而不是插入段落
                force_br_newlines: false,
                //当返回或进入 Mozilla/Firefox 时,这个选项可以打开/关闭段落的建立
                force_p_newlines: false,
                //这个选项控制是否将换行符从输出的 HTML 中去除。选项默认打开,因为许多服务端系统将换行转换成 <br />,因为文本是在无格式的 textarea 中输入的。使用这个选项可以让所有内容在同一行。
                remove_linebreaks: false,
                //不能把这个设置去掉,不然图片路径会出错
                relative_urls: false,
                //不允许拖动大小
                resize: false,
                font_formats: "宋体=宋体;黑体=黑体;仿宋=仿宋;楷体=楷体;隶书=隶书;幼圆=幼圆;Arial=arial,helvetica,sans-serif;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Tahoma=tahoma,arial,helvetica,sans-serif;Times New Roman=times new roman,times;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats",
                fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt"
            });

            
        });

    </script>
    <%-- 编辑器结束--%>
<textarea id="content" name="content"></textarea>

获取编辑器内容:

tinymce.activeEditor.getContent()

编辑器内容赋值:

//文本编辑器 赋值
$("#content").html("<html></html>");

二、后台部分

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.IO;

namespace Web.Controllers
{
    public class CommonController : Controller
    {
        public static string[] LimitPictureType = { ".PNG", ".JPG", ".JPEG", ".BMP", ".ICO" };
        public static string[] LimitFIleType = { ".DOC", ".DOCX", ".PPT", ".PPTX", ".PDF", ".XLS", ".XLSX", ".TXT", ".ZIP", ".RAR", ".7Z", ".MP4", ".AVI", ".RMVB" };

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpLoadImg(HttpPostedFileBase formFile)
        {
            var data = new MessageModel<string>();
            if (formFile == null)
            {
                data.success = false;
                data.msg = "图片保存失败";
                return Json(data);
            }
            string _path = "_FileUpLoad";
            //文件名
            var currentPictureWithoutExtension = Path.GetFileNameWithoutExtension(formFile.FileName);
            //扩展名
            var currentPictureExtension = Path.GetExtension(formFile.FileName).ToUpper();

            string savePath = Server.MapPath("~/"+ _path) + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            if (LimitPictureType.Contains(currentPictureExtension))
            {
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }

                string name = DateTime.Now.ToString("yyyyMMddHHmmss") + currentPictureExtension.ToLower();
                savePath += name;
                formFile.SaveAs(savePath);
                data.success = true;
                data.msg = "图片保存成功";
                //返回路径
                data.response = "/" + _path + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + name;
            }
            else
            {
                data.success = false;
                data.msg = "图片保存失败";
            }
            return Json(data);

        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpLoadFile(HttpPostedFileBase formFile)
        {
            var data = new MessageModel<string>();
            if (formFile == null)
            {
                data.success = false;
                data.msg = "文件保存失败";
                return Json(data);
            }
            string _path = "_FileUpLoad";
            //文件名
            var currentPictureWithoutExtension = Path.GetFileNameWithoutExtension(formFile.FileName);
            //扩展名
            var currentPictureExtension = Path.GetExtension(formFile.FileName).ToUpper();

            string savePath = Server.MapPath("~/" + _path) + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            if (LimitFIleType.Contains(currentPictureExtension))
            {
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }

                string name = DateTime.Now.ToString("yyyyMMddHHmmss") + currentPictureExtension.ToLower();
                savePath += name;
                formFile.SaveAs(savePath);
                data.success = true;
                data.msg = "文件保存成功";
                //返回路径
                data.response = "/" + _path + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + name;
            }
            else
            {
                data.success = false;
                data.msg = "文件保存失败";
            }
            return Json(data);

        }

    }
}

 

Tinymce 地址:

https://files.cnblogs.com/files/shuaichao/tinymce.zip

posted @ 2020-11-04 17:09  岳帅超  阅读(228)  评论(0编辑  收藏  举报