MVC.Net5:添加Tinymce的图片上传功能

Tinymce是目前几个主流的Web文本编辑器之一,不过它的图片上传功能是要收费的,而其它几个免费的上传图片的插件支持的都是PHP。那么就只能自己动手写一个了(源代码下载)。

准备工作如下:
1.    创建一个MVC.Net的项目(废话)
2.    添加jQuery类库。我使用的是jQuery 1.11.1版本。可以通过NuGet直接加入到项目中。

Install-Package jQuery -Version 1.11.1

3.    添加jQuery UI类库。下载地址如下:http://jqueryui.com/download/ 此处我们只用到它的Dialog Widget。
4.    添加Tinymce类库。我使用的是Tinymce 3.5.8版本。可以通过NuGet直接加入到项目中。

Install-Package TinyMCE -Version 3.5.8

5.    添加Tinymce的中文语言包,下载地址:http://www.tinymce.com/i18n3x/index.php?ctrl=lang&act=download&pr_id=1
6.    准备一个上传图片的ICON,这里我直接copy了cnblogs的。:D


准备工作结束,这时的项目结构如下:


接下来开始代码部分:
1.    创建html文件

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Tinymce with upload feature's demo</title>
</head>
<body>
    <div>
        <label>Tinymce with upload feature's demo</label>
        <br />
        <textarea name="content" id="content" cols="50" rows="20"></textarea>
    </div>
</body>
</html>

2.    引入需要的js和css文件。

    <link type="text/css" href="/Scripts/jquery-ui-1.11.0/jquery-ui.min.css" rel="stylesheet" />
    <script type="text/javascript" src="/Scripts/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="/Scripts/tinymce/tiny_mce.js"></script>
    <script type="text/javascript" src="/Scripts/jquery-ui-1.11.0/jquery-ui.min.js"></script>

3.    将Tinymce初始化

    <script type="text/javascript">
        tinyMCE.init({
            language: "cn",
            mode: "textareas",
            theme: "advanced",
            plugins: "emotions,spellchecker,advhr,insertdatetime,preview",

            // Theme options - button# indicated the row# only
            theme_advanced_buttons1: "newdocument,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,fontselect,fontsizeselect,formatselect",
            theme_advanced_buttons2: "cut,copy,paste,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,|,code,preview,|,forecolor,backcolor",
            theme_advanced_buttons3: "insertdate,inserttime,|,spellchecker,advhr,,removeformat,|,sub,sup,|,charmap,emotions",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "bottom",
            theme_advanced_resizing: true
        });
    </script>

4.    这时textarea控件应该已经变成Tinymce编辑器了。

5.    现在开始创建上传图片的插件。先在Tinymce的plugins目录中创建如下目录和文件。

1)    Img.gif就是上传图片的ICON
2)    Editor_plugin.js的代码如下(注:此处代码copy自cnblogs,做了少量修改):

(function () {
    tinymce.PluginManager.requireLangPack('uploadImage');

    tinymce.create('tinymce.plugins.uploadImagePlugin', {
        /**
        * Initializes the plugin, this will be executed after the plugin has been created.
        * This call is done before the editor instance has finished it's initialization so use the onInit event
        * of the editor instance to intercept that event.
        *
        * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
        * @param {string} url Absolute URL to where the plugin is located.
        */
        init: function (ed, url) {
            // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample');
            ed.addCommand('mceuploadImage', function () {
                imageUploadWindow();
            });

            // Register example button
            ed.addButton('uploadImage', {
                title: '上传图片',
                cmd: 'mceuploadImage',
                image: url + '/img/img.gif'
            });

            // Add a node change handler, selects the button in the UI when a image is selected
            ed.onNodeChange.add(function (ed, cm, n) {
                cm.setActive('uploadImage', n.nodeName == 'img');
            });            
        },

        /**
        * Creates control instances based in the incomming name. This method is normally not
        * needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons
        * but you sometimes need to create more complex controls like listboxes, split buttons etc then this
        * method can be used to create those.
        *
        * @param {String} n Name of the control to create.
        * @param {tinymce.ControlManager} cm Control manager to use inorder to create new control.
        * @return {tinymce.ui.Control} New control instance or null if no control was created.
        */
        createControl: function (n, cm) {
            return null;
        },

        /**
        * Returns information about the plugin as a name/value array.
        * The current keys are longname, author, authorurl, infourl and version.
        *
        * @return {Object} Name/value array containing information about the plugin.
        */
        getInfo: function () {
            return {
                longname: 'uploadImage plugin',
                author: 'cnblogs',
                authorurl: 'http://www.cnblogs.com',
                infourl: 'http://www.cnblogs.com',
                version: "1.0"
            };
        }
    });

    // Register plugin
    tinymce.PluginManager.add('uploadImage', tinymce.plugins.uploadImagePlugin);
})();

3)    cn.js的代码:

tinyMCE.addI18n('zh.uploadImage_cn', {
    desc: '上传图片'
});

6.    接着回到刚才的HTML页面,添加如下JS代码:

        var imageUploadWindow = function () {
            $("#dialog-confirm").dialog({
                resizable: false,
                width: 350,
                height: 200,
                modal: true,
                buttons: {
                    "确定": function () {
                        $(this).dialog("close");

                        var formObj = $('#updateForm');
                        var formURL = formObj.attr("action");

                        if (window.FormData !== undefined)  // for HTML5 browsers
                        {
                            var formData = new FormData();
                            jQuery.each($('input[name^="Photo"]')[0].files, function (i, file) {
                                formData.append('photo', file);
                            });
                            //formData.append('photo',);

                            $.ajax({
                                url: formURL,
                                type: 'POST',
                                data: formData,
                                async: false,
                                mimeType: "multipart/form-data",
                                contentType: false,
                                cache: false,
                                processData: false,
                                success: function (data, textStatus, jqXHR) {
                                    var ed = tinyMCE.get('content');
                                    var newNode = ed.dom.createHTML('img', { src: '/Content/images/' + data });  // create img node
                                    if (tinymce.isIE) {
                                        tinyMCE.activeEditor.selection.moveToBookmark(actualCaretPositionBookmark);
                                        ed.execCommand('mceInsertContent', false, newNode);
                                    } else {
                                        ed.execCommand('mceInsertContent', false, newNode);
                                    }
                                },
                                error: function (jqXHR, textStatus, errorThrown) {

                                }
                            });
                        }
                        else  //for olden browsers
                        {
                            //generate a random id
                            var iframeId = 'unique' + (new Date().getTime());

                            //create an empty iframe
                            var iframe = $('<iframe src="javascript:false;" name="' + iframeId + '" />');

                            //hide it
                            iframe.hide();

                            //set form target to iframe
                            formObj.attr('target', iframeId);

                            //Add iframe to body
                            iframe.appendTo('body');
                            iframe.load(function (e) {
                                var doc = getDoc(iframe[0]);
                                var docRoot = doc.body ? doc.body : doc.documentElement;
                                var data = docRoot.innerHTML;
                                //data is returned from server.

                            });
                        }
                    },
                    "取消": function () {
                        $(this).dialog("close");
                    }
                }
            });
        };

    function getDoc(frame) {
        var doc = null;

        // IE8 cascading access check
        try {
            if (frame.contentWindow) {
                doc = frame.contentWindow.document;
            }
        } catch (err) {
        }

        if (doc) { // successful getting content
            return doc;
        }

        try { // simply checking may throw in ie8 under ssl or mismatched protocol
            doc = frame.contentDocument ? frame.contentDocument : frame.document;
        } catch (err) {
            // last attempt
            doc = frame.document;
        }
        return doc;
    }

7.    修改Tinymce的初始化代码,加入uploadImage插件。

        tinyMCE.init({
            language: "cn",
            mode: "textareas",
            theme: "advanced",
            plugins: "emotions,spellchecker,advhr,insertdatetime,preview,uploadImage",

            // Theme options - button# indicated the row# only
            theme_advanced_buttons1: "newdocument,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,fontselect,fontsizeselect,formatselect",
            theme_advanced_buttons2: "cut,copy,paste,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,uploadImage,|,code,preview,|,forecolor,backcolor",
            theme_advanced_buttons3: "insertdate,inserttime,|,spellchecker,advhr,,removeformat,|,sub,sup,|,charmap,emotions",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "bottom",
            theme_advanced_resizing: true,
            setup: function (ed) {
                ed.onKeyUp.add(function (ed, e) {
                    actualCaretPositionBookmark = tinyMCE.activeEditor.selection.getBookmark();
                });
                ed.onClick.add(function (ed, e) {
                    actualCaretPositionBookmark = tinyMCE.activeEditor.selection.getBookmark();
                });
            }
        });

8.    添加上传图片的弹出窗口

        <div id="dialog-confirm" title="上传图片" style="display:none;">
            <form action="/File/Upload" method="post" role="form" enctype="multipart/form-data" name="updateForm" id="updateForm">
                <input type="file" name="Photo" accept="image/*">
            </form>
        </div>

9.    创建FileController.cs,代码如下:

        public ActionResult Upload()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase photo)
        {
            if (photo != null)
            {
                var path = Server.MapPath("/Content/images");
                var fileName = "p" + DateTime.Now.Ticks.ToString() +".jpg";
                photo.SaveAs(Path.Combine(path, fileName));
                ViewBag.FileName = fileName;
                return View();
            }
            else
            {
                ViewBag.FileName = "";
                return View();
            }
        }

10.    最后创建Upload.cshtml文件,内容就是一行代码:

@ViewBag.fileName

11.    OK,效果如下:



其实整个代码还有需要改善的地方,比如实现文件上传时的等待效果。这里就不展开了。

转载于:https://www.cnblogs.com/ilovewindy/p/3823069.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
详情:http://blog.csdn.net/spritenet/article/details/8085378 这个编辑器是我中午翻资料偶然看见的,既然有些人对他评价还可以,因此我就拿来试了试 网上的一些资料基本上都停留在2011年,而且是这个抄这个,这个抄那个,真正有用的并不多,在此我参考了以下几位同学的博客,再次谢谢各位 http://blog.csdn.net/chenloveyue/article/details/7039913 http://blog.csdn.net/salc3k/article/details/5341593 http://hi.baidu.com/honfei/item/267e3dd128d934866dce3fbe http://www.hnonl.com/jonllen/article/66.aspx?display=2 我用的版本是tinymce_3_0_8 官网上有最近版本的,但是木有汉化,而且也没找到相应的说明文档 总体说来这个Tinymce和KindEditor 配置使用起来都比较简单,而且Tinymce还提供两种定义好的模式,一个是专业版,就是所有功能都有的,一种是精简版,只有6.7个功能,当然Tinymce最大的优势在于可以很方便的调整控件,通过plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager",就可以很轻松的控制要显示的功能 说说目前发现的缺点: 1.没有图片上传功能 2.没有图文混排 3.css的定义太多 4.最要命的是我居然发现没有设置字体颜色和背景颜色的控件,这让我很纳闷 图片如下: 详情:http://blog.csdn.net/spritenet/article/details/8085378
TinyMCE是一个开源的富文本编辑器,它提供了许多强大的功能,包括上传图片。要在TinyMCE添加图片上传功能,需要以下步骤: 1. 在TinyMCE的初始化代码中,添加一个图片上传插件。可以使用现成的插件,如`image`插件或自定义插件。 ```javascript tinymce.init({ selector: 'textarea', plugins: 'image', toolbar: 'image', image_title: true, automatic_uploads: true, file_picker_types: 'image', file_picker_callback: function (cb, value, meta) { var input = document.createElement('input'); input.setAttribute('type', 'file'); input.setAttribute('accept', 'image/*'); input.onchange = function () { var file = this.files[0]; var reader = new FileReader(); reader.onload = function () { var id = 'blobid' + (new Date()).getTime(); var blobCache = tinymce.activeEditor.editorUpload.blobCache; var base64 = reader.result.split(',')[1]; var blobInfo = blobCache.create(id, file, base64); blobCache.add(blobInfo); cb(blobInfo.blobUri(), { title: file.name }); }; reader.readAsDataURL(file); }; input.click(); } }); ``` 2. 在服务器上设置一个处理上传图片的脚本。这个脚本应该接收上传的图片文件,并将其保存到服务器上的某个位置。 3. 将脚本的URL添加TinyMCE的初始化代码中,以便在上传图片时使用。 ```javascript tinymce.init({ ... images_upload_url: 'upload.php', ... }); ``` 以上是一个基本的图片上传功能的实现步骤,你可以根据自己的需求进行相应的修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值