ASP.NET MVC4實現TinyMCE 4.0.20自定義上傳功能

tinymce 插件不提供免費的本地圖片上傳功能,因此本身將uploadify這個上傳插件整合到tinymce,實現本地上傳,還用到了jquery.ui插件,先展現所有的代碼javascript

@model TinyMCEUpload.Models.TinyMCEModels
<script type="text/javascript">
    $(document).ready(function () {
        var tinymceEditor;
        tinymce.init({
            selector: "textarea#content",
            auto_focus: "content",
            language: "zh_CN",
            theme: "modern",
            plugins: [
                "advlist autolink lists link image charmap preview",
                "searchreplace visualblocks fullscreen",
                "insertdatetime media table contextmenu paste",
                "emoticons textcolor"
            ],
            toolbar1: "undo redo | styleselect | fontselect | fontsizeselect | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent",
            toolbar2: "fullscreen preview | forecolor backcolor emoticons | table | link image media | mybutton",
            setup: function (editor) {
                editor.addButton('mybutton', {
                    text: '上傳圖片',
                    icon: false,
                    onclick: function () {
                        tinymceEditor = editor;
                        $("#uploadofedit").dialog({
                            modal: true,
                            resizable: false,
                            width: 400,
                            height: 200,
                            dialogClass: "mceuploadify"
                        });
                    }
                });
            },
            //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"
        });

        $("#tinymceuploadify").uploadify({
            'swf': '../../uploadify/uploadify.swf',
            'buttonText': '上傳本地圖片',
            'uploader': '/Home/Upload',
            'auto': true,
            'method': 'post',
            'multi': false,
            'onUploadSuccess': function (event, data, flag) {
                var img = "<img  src='../../File/" + data + "'>";
                tinymceEditor.insertContent(img);
                setTimeout(function () {
                    $("#uploadofedit").dialog('close');
                }, 1000);
            },
            'onUploadError': function () {
                setTimeout(function () {
                    $("#uploadofedit").dialog('close');
                }, 1000);
                alert("上傳失敗");
            }
        });
    });
</script>
<div>
    <form method="post" action="/Home/Test">
        <textarea id="content" name="content" style="width: 100%; height: 600px;"></textarea>
        <input type="submit" value="提交" />
    </form>
</div>
<div id='uploadofedit' style="display: none;">
    <input type='file' name='tinymceuploadify' id='tinymceuploadify' />
    <label>只能上傳單張10M如下的 png、jpg、gif 格式的圖片</label>
</div>
View Code

接下來分步驟來分析html

1  先實如今tinymce插件上添加自定義按鈕java

toolbar2: " mybutton",
            setup: function (editor) {
                editor.addButton('mybutton', {
                    text: '上傳圖片',
                    icon: false,
                    onclick: function () {
                       
                        });
                    }
                });
            },
View Code

2.初始化uploadify插件jquery

$("#tinymceuploadify").uploadify({
            'swf': '../../uploadify/uploadify.swf',
            'buttonText': '上傳本地圖片',
            'uploader': '/Home/Upload',
            'auto': true,
            'method': 'post',
            'multi': false,
            'onUploadSuccess': function (event, data, flag) {
                var img = "<img  src='../../File/" + data + "'>";
                tinymceEditor.insertContent(img);
                setTimeout(function () {
                    $("#uploadofedit").dialog('close');
                }, 1000);
            },
            'onUploadError': function () {
                setTimeout(function () {
                    $("#uploadofedit").dialog('close');
                }, 1000);
                alert("上傳失敗");
            }
        });
View Code

3.在點擊自定義按鈕後啓用jquery-ui的dialog插件調出上傳對話框web

setup: function (editor) {
                editor.addButton('mybutton', {
                    text: '上傳圖片',
                    icon: false,
                    onclick: function () {
                        tinymceEditor = editor;
                        $("#uploadofedit").dialog({
                            modal: true,
                            resizable: false,
                            width: 400,
                            height: 200,
                            dialogClass: "mceuploadify"
                        });
                    }
                });
            }
View Code

至此前臺部分OK了,接下來是後臺數據庫

1.後臺接收用戶上傳的圖片mvc

[HttpPost]
        public ContentResult Upload(HttpPostedFileBase Filedata)
        {
            string result = string.Empty;
            string folder = Server.MapPath("~/File/");
            string time = DateTime.Now.ToString("yyyyMMddHHmmssff");//獲取時間
            string extension = System.IO.Path.GetExtension(Filedata.FileName);//獲取擴展名
            string newFileName = time + extension;//重組成新的文件名
            if (!System.IO.Directory.Exists(folder))
                System.IO.Directory.CreateDirectory(folder);

            Filedata.SaveAs(folder + "\\" + newFileName);

            return Content(newFileName);
        }
View Code

2.接收tinymce插件的內容(我這裏簡單的用記事原本替代數據庫),而後再從記事本中把內容讀出來呈現到另外一個頁面上ide

/// <summary>
        /// 接收tinymce插件的內容
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult Test(TinyMCEModels model)
        {
            var path = Server.MapPath("~/File/123.txt");
            var str = System.IO.File.ReadAllText(path);
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }

            System.IO.File.WriteAllText(path, model.content);

            return RedirectToAction("Show");
        }

        /// <summary>
        /// 將記事本的內容讀出來,從新加載到頁面上
        /// </summary>
        /// <returns></returns>
        public ActionResult Show()
        {
            var str = System.IO.File.ReadAllText(Server.MapPath("~/File/123.txt"));
            ViewBag.str = str.Trim();
            return View();
        }
View Code

由於在mvc4中爲了防止腳本攻擊,默認是不容許有html標記的內容傳到後臺的,因此我創建了一個TinyMCEModels,在content屬性上加上AllowHtml標記(在System.Web.Mvc命名空間下),這樣就好了post

public class TinyMCEModels
    {
        [AllowHtml]
        public string content { get; set; }
    }
View Code

 

 源碼  http://files.cnblogs.com/guzhehang/TinyMCEUpload.rarui

相關文章
相關標籤/搜索