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,效果如下:

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

MVC.Net5:添加Tinymce的图片上传功能的更多相关文章

  1. Spring+SpringMVC+MyBatis+easyUI整合优化篇(七)图片上传功能

    日常啰嗦 前一篇文章<Spring+SpringMVC+MyBatis+easyUI整合优化篇(六)easyUI与富文本编辑器UEditor整合>讲了富文本编辑器UEditor的整合与使用 ...

  2. vue 图片上传功能

    这次做了vue页面的图片上传功能,不带裁剪功能的! 首先是html代码,在input框上添加change事件,如下:   <ul class="clearfix">   ...

  3. 前端丨如何使用 tcb-js-sdk 实现图片上传功能

    前言 tcb-js-sdk 让开发者可以在网页端使用 JavaScript 代码服务访问云开发的服务,以轻松构建自己的公众号页面或者独立的网站等 Web 服务.本文将以实现图片上传功能为例,介绍 tc ...

  4. thinkphp达到UploadFile.class.php图片上传功能

    片上传在站点里是非经常常使用的功能.ThinkPHP里也有自带的图片上传类(UploadFile.class.php) 和图片模型类(Image.class.php).方便于我们去实现图片上传功能,以 ...

  5. PHP语言学习之php做图片上传功能

    本文主要向大家介绍了PHP语言学习之php做图片上传功能,通过具体的内容向大家展示,希望对大家学习php语言有所帮助. 今天来做一个图片上传功能的插件,首先做一个html文件:text.php < ...

  6. [Ting's笔记Day8]活用套件carrierwave gem:(3)Deploy图片上传功能到Heroku网站

    前情提要: 身为Ruby新手村民,创造稳定且持续的学习步调很重要,我用的方法就是一周在IT邦写三篇笔记,希望藉由把笔记和遇到的bug记录下来的过程,能帮助到未来想用Ruby on Rails架站的新手 ...

  7. H5 利用vue实现图片上传功能。

    H5的上传图片如何实现呢? 以下是我用vue实现的图片上传功能,仅供参考. <!DOCTYPE html> <html> <head> <meta chars ...

  8. 给DEDECMS广告管理中增加图片上传功能

    dedecms的广告管理功能稍微有点次,本文就是在dedecms广告管理原有的基础上增加广告图片上传功能. 安装方法,对应自己的dedecms版本下载对应的编码然后解压把里面的文件放在后台目录覆盖即可 ...

  9. django中tinymce添加图片上传功能

    主要参考以下: https://pixabay.com/en/blog/posts/direct-image-uploads-in-tinymce-4-42/ http://blog.csdn.net ...

随机推荐

  1. Oracle(一)

    1.树形表,查询 所有的下边的记录 情景:根据当前记录的ID,要查询其所有子记录,每个子记录再查询当前子记录的所有子记录,如果有的话,一直迭代下去 当前表结构: CREATE TABLE " ...

  2. 题解报告:hdu 2516 取石子游戏(斐波那契博弈)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2516 Problem Description 1堆石子有n个,两人轮流取.先取者第1次可以取任意多个, ...

  3. WinForm窗体项目 之 MySchool管理系统终极版

    学习WinForm窗体程序也有一段时间了,今天就来尝试着来一个项目热热身~ 在我们通常使用的MySchool管理中,不外乎这几种功能:增.删.改.查.改密码 在过去的C#中确实是挺简单的,但是在学习了 ...

  4. 将电脑浏览器User-Agent识别改成手机浏览器UA几种简单方法

    第一种方法:修改浏览器的快捷方式 右击桌面上的Chrome浏览器图标,在弹出的右键菜单中选择“复制”,复制一个图标副本到桌面.右击该副本,选择“属性”,打开相应的对话框,在“目标”文本框的字符后面添加 ...

  5. 个人作业——Alpha项目测试

    这个作业属于哪个课程 https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass1/ 这个作业要求在哪里 https://edu.cnbl ...

  6. 删除过期备份报错RMAN-06207 RMAN-06208解决方案

    RMAN备份日志中出现了警告 日志文件目录如下: [root@erpdbs rmanback]# ll total 88 -rw-r--r-- 1 oraprod dba 81011 Sep 7 22 ...

  7. vue iView 打包后 字体图标不显示

    问题描述: 今天webpack打包后发现iView 字体图标不显示 解决方案: build/webpack.prod.conf.js 这个文件里面 module: { rules: utils.sty ...

  8. MSSQL高并发下生成连续不重复的订单号

    一.确定需求 只要做过开发的基本上都有做过订单,只要做过订单的基本上都要涉及生成订单号,可能项目订单号生成规则都不一样,但是大多数规则都是连续增长. 所以假如给你一个这样的需求,在高并发下,以天为单位 ...

  9. day10-函数基础知识

    函数 什么是函数 把工具事先准备好,然后下次使用的时候,直接使用就行了.我们的函数就是工具 为何用函数 1.遇到重复的功能只能重复编写实现代码,代码冗余 2.功能需要扩展时,需要找出所有实现该功能的地 ...

  10. Redis 之order set有序集合结构及命令详解

    1.zadd key score1 value1 score2 value2  添加元素 2.zrem key value1 value2 ..  删除集合中的元素 3.zremrangebyscor ...