【NKeditor】富文本编辑器上传图片

  • 【NKeditor】富文本编辑器上传图片已关闭评论
  • 88 次浏览
  • A+
所属分类:Web前端
摘要

使用NKeditor富文本编辑器上传图片,同时上传到七牛云存储上。后端语言使用ThinkPHP。


目的:

使用NKeditor富文本编辑器上传图片,同时上传到七牛云存储上。后端语言使用ThinkPHP。

效果

【NKeditor】富文本编辑器上传图片

实现方法:

1、下载NKeditor插件库

下载地址:NKeditor: NKedtior是一款优秀的轻量级Web编辑器,基于 Kindedior 二次开发

里面的文档demo写的比较详细,可以直接使用,不过里面上传七牛云的代码不能用,所以我是自己写的。 

2、部署

 把下载的NKeditor插件库放到/public/文件夹下。

  <link href="/NKeditor/libs/bootstrap/bootstrap.min.css" rel="stylesheet">   <div role="tabpanel" class="tab-pane fade" id="default">     <form name="example" method="post">         <textarea name="content2" style="width:900px;height:500px;visibility:hidden;"></textarea>     </form> </div>     <script charset="utf-8" src="/NKeditor/NKeditor-all.js"></script> <!-- 如果你不需要使用批量图片上传,涂鸦功能和文件管理功能,就不需要引入 jquery --> <script charset="utf-8" src="/NKeditor/libs/jquery.min.js"></script> <!-- JDialog是一款优秀的漂亮,轻量级的js弹出框插件 不是必须引入的,如果不引入则使用默认的 window.alert() 来弹出提示信息 --> <script charset="utf-8" src="/NKeditor/libs/JDialog/JDialog.min.js"></script> <script src="/NKeditor/libs/bootstrap/bootstrap.min.js"></script>   <script> KindEditor.ready(function(K) {          K.create('textarea[name="mytextarea"]', {         uploadJson : '/teacher/qiniu/uploadImg',         // fileManagerJson : K.basePath+'php/qiniu/file_manager_json.php',         dialogOffset : 0, //对话框距离页面顶部的位置,默认为0居中,         allowFileManager : false,         allowImageUpload : true,         allowMediaUpload : false,         items : ['source','undo','redo','preview','print','code','quote','plainpaste','justifyleft','justifycenter','justifyright','justifyfull','insertorderedlist','insertunorderedlist','indent','outdent','subscript','superscript','clearhtml','quickformat','selectall','formatblock','fontname','fontsize','forecolor','hilitecolor','bold','italic','underline','strikethrough','lineheight','removeformat','image','table','tablecell','hr','baidumap','pagebreak','link','unlink','fullscreen'         ],         afterCreate : function() {             var self = this;             K.ctrl(document, 13, function() {                 self.sync();                 K('form[name=example]')[0].submit();             });             K.ctrl(self.edit.doc, 13, function() {                 self.sync();                 K('form[name=example]')[0].submit();             });         },         showHelpGrid: false, // 是否显示输入辅助线         themeType : "black", //主题         //错误处理 handler         errorMsgHandler : function(message, type) {             try {                 JDialog.msg({type:type, content:message, timer:2000});             } catch (Error) {                 alert(message);             }         }     }); }) </script>

后端代码:返回值是json,返回格式与下面代码一致。

<?php namespace appteachercontroller; use thinkController; use QiniuAuth as Auth; use QiniuStorageBucketManager; use QiniuStorageUploadManager;   /**  * 七牛云操作  */ class Qiniu extends Base {       public function uploadImg()     {         error_reporting(0);           vendor('qiniu.autoload');         $accessKey = config('ACCESSKEY');         $secretKey = config('SECRETKEY');         $bucket = config('BUCKET');         $domain = config('DOMAIN');           $fileType = trim($_GET['fileType']);           if (empty($fileType)) {             $fileType = "image";         }           // 要上传图片的本地路径         $filePath = $_FILES['imgFile']['tmp_name'];           $ext = substr($_FILES['imgFile']['name'],strrpos($_FILES['imgFile']['name'],'.')+1);  //文件后缀          // 后缀大写转换成小写          $ext = strtolower($ext);           $format = array('png','jpg','gif','jpeg','bmp','tif','svg','webp');  //允许上传的格式         if (!in_array($ext,$format)) {             $result = array(                 'code'=>'001',                 'message'=>'格式错误'             );         }           // 上传到七牛后保存的文件名         $key = 'shouyi_img/'.substr(md5($filePath) , 0, 5) .'/'. date('YmdHis') . rand(0, 9999) . '.' . $ext;           // 构建鉴权对象         $auth = new Auth($accessKey, $secretKey);           $token = $auth->uploadToken($bucket);           // 初始化 UploadManager 对象并进行文件的上传         $uploadMgr = new UploadManager();           // 调用 UploadManager 的 putFile 方法进行文件的上传         list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);           // var_dump($ret);         if ($err !== null) {               $result = array(                 'code'=>'001',                 'message'=>'上传失败'             );           } else {             $result = array(                 'code'=>'000',                 'message'=>'上传成功'.$_FILES['imgFile']['name'],                 'data'=>array('url' => $domain . $ret['key']),             );         }           die(json_encode($result,JSON_UNESCAPED_UNICODE));     } }

文件上传到七牛云可参看之前写的文章:【七牛云】使用PHP把文件上传到七牛云_php 七牛云上传_下页、再停留的博客-CSDN博客

4、自定义工具栏

在items根据需要添加相应的功能

    source : 'HTML代码',     preview : '预览',     undo : '后退(Ctrl+Z)',     redo : '前进(Ctrl+Y)',     cut : '剪切(Ctrl+X)',     copy : '复制(Ctrl+C)',     paste : '粘贴(Ctrl+V)',     plainpaste : '粘贴为无格式文本',     wordpaste : '从Word粘贴',     selectall : '全选(Ctrl+A)',     justifyleft : '左对齐',     justifycenter : '居中',     justifyright : '右对齐',     justifyfull : '两端对齐',     insertorderedlist : '编号',     insertunorderedlist : '项目符号',     indent : '增加缩进',     outdent : '减少缩进',     subscript : '下标',     superscript : '上标',     formatblock : '段落',     fontname : '字体',     fontsize : '文字大小',     forecolor : '文字颜色',     hilitecolor : '文字背景',     bold : '粗体(Ctrl+B)',     italic : '斜体(Ctrl+I)',     underline : '下划线(Ctrl+U)',     strikethrough : '删除线',     removeformat : '删除格式',     image : '图片',     multiimage : '批量图片上传',     graft : '涂鸦',     flash : 'Flash',     media : '视音频',     table : '表格',     tablecell : '单元格',     hr : '插入横线',     emoticons : '插入表情',     link : '超级链接',     unlink : '取消超级链接',     fullscreen : '全屏显示',     about : '关于',     print : '打印(Ctrl+P)',     filemanager : '文件空间',     code : '插入程序代码',     quote : '插入引用',     map : 'Google地图',     baidumap : '百度地图',     lineheight : '行距',     clearhtml : '清理HTML代码',     pagebreak : '插入分页符',     quickformat : '一键排版',     insertfile : '插入文件',     template : '插入模板'