自定义qiniu kindeditor

后端



import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.util.Auth;
import com.twj.sysu.common.controller.BaseController;

@RestController
@RequestMapping("/qingniu")
public class KindEditorAuthController extends BaseController {
    @RequestMapping("QiniuUpToken")
    public void QiniuUpToken(@RequestParam String suffix,HttpServletRequest request, HttpServletResponse response) throws Exception{
		PrintWriter out = null;
		Map<String,Object> result = new HashMap<String,Object>();
		try {
            String accessKey = "******";    //访问秘钥
            String secretKey = "******";    //授权秘钥
            String bucket = "******";       //存储空间名称
            Auth auth = Auth.create(accessKey, secretKey);      //验证七牛云身份是否通过
            out = response.getWriter();
		    //生成凭证
		    String upToken = auth.uploadToken(bucket);
		    result.put("token", upToken);
		    // 是否可以上传的图片格式
		    /*boolean flag = false;  
		    String [] imgTypes= new String[]{"jpg","jpeg","bmp","gif","png"};
		    for(String fileSuffix :imgTypes) {
				if(suffix.substring(suffix.lastIndexOf(".") + 1).equalsIgnoreCase(fileSuffix)) {
				    flag = true;
				    break;
				}
		    }
		    if(!flag) {
			throw new Exception("图片:" + suffix + " 上传格式不对!");
		    }*/
	       //生成实际路径名
           String randomFileName=UUID.randomUUID().toString() +suffix;
           result.put("imgUrl", randomFileName);
           result.put("success", 0);
           out.write(JSONObject.toJSONString(result));
		   } catch (Exception e) {
				 result.put("success", 400);
				 result.put("message", "获取凭证失败,"+e.getMessage());
				 out.write(JSONObject.toJSONString(result));
	       }
    }
}

 

对上传操作进行封装

/**
 * 针对副文本编辑器kindeditor,从后台获取Token,上传文件到七牛
 */
var ajaxFileUpload= function() {
	var kindFileUrl = "";
    var fileName = $(".ke-upload-file").val();                        //上传的本地文件绝对路径
	var suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length);	//后缀名
	var file = $(".ke-upload-file").get(0).files[0];	                                        //上传的文件
	//七牛云上传
	var result = Sysu.GET({url:"/qingniu/QiniuUpToken",map:{"suffix":suffix}});
	if(result.success == 0) {
         var observer = {                         //设置上传过程的监听函数
              next(result){                        //上传中(result参数带有total字段的 object,包含loaded、total、percent三个属性)
                  Math.floor(result.total.percent); //查看进度[loaded:已上传大小(字节);total:本次上传总大小;percent:当前上传进度(0-100)]
              },
              error(err){                          //失败后
                  alert(err.message);
              },
              complete(res1){                      //成功后
				  //$("#img").attr("src","http://sysu.teweijia.com/"+result.imgUrl+"?imageView2/2/h/100");
              }
          };
          var putExtra = {
              fname: "",                          //原文件名
              params: {},                         //用来放置自定义变量
              mimeType: null                      //限制上传文件类型
          };
          var config = {
              region:qiniu.region.z2,             //存储区域(z0: 代表华东;不写默认自动识别)
              concurrentRequestLimit:3            //分片上传的并发请求量
          };
          var observable = qiniu.upload(file,result.imgUrl,result.token,putExtra,config);
          observable.subscribe(observer)// 上传开始
    } else {
		  alert("获取Token失败");
	}
	return result.imgUrl;
}

 

kindeditor自定义插件

plugins目录下

复制image改名为diy_video 和diy_video.js

KindEditor.plugin('diy_video', function (K) {
		var self = this, name = 'diy_video',
		allowImageUpload = K.undef(self.allowImageUpload, true),
		allowImageRemote = K.undef(self.allowImageRemote, true),
		formatUploadUrl = K.undef(self.formatUploadUrl, true),
		allowFileManager = K.undef(self.allowFileManager, false),
		uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
		imageTabIndex = K.undef(self.imageTabIndex, 0),
		imgPath = self.pluginsPath + 'image/images/',
		extraParams = K.undef(self.extraFileUploadParams, {}),
		filePostName = K.undef(self.filePostName, 'imgFile'),
		fillDescAfterUploadImage = K.undef(self.fillDescAfterUploadImage, false),
		lang = self.lang(name + '.');

	self.plugin.imageDialog = function(options) {
		var imageUrl = options.imageUrl,
			imageWidth = K.undef(options.imageWidth, ''),
			imageHeight = K.undef(options.imageHeight, ''),
			imageTitle = K.undef(options.imageTitle, ''),
			imageAlign = K.undef(options.imageAlign, ''),
			showRemote = K.undef(options.showRemote, true),
			showLocal = K.undef(options.showLocal, true),
			tabIndex = K.undef(options.tabIndex, 0),
			clickFn = options.clickFn;
		var target = 'kindeditor_upload_iframe_' + new Date().getTime();
		var hiddenElements = [];
		for(var k in extraParams){
			hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />');
		}
		var html = [
			'<div style="padding:20px;">',
				//tabs
				'<div class="tabs"></div>',
				//网络图片 image - start
				'<div class="tab1" style="display:none;">',
					//url
					'<div class="ke-dialog-row">',
					'<label for="remoteUrl" style="width:60px;">网络图片</label>',
					'<input type="text" id="remoteUrl" class="ke-input-text" name="url" value="" style="width:200px;" /> &nbsp;',
					'<span class="ke-button-common ke-button-outer">',
					'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + 'lang.viewServer' + '" />',
					'</span>',
					'</div>',
					//size
					'<div class="ke-dialog-row">',
					'<label for="remoteWidth" style="width:60px;">' + '大小' + '</label>',
					'宽' + ' <input type="text" id="remoteWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ',
					'高' + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ',
					'<img class="ke-refresh-btn" src="' + imgPath + 'refresh.png" width="16" height="16" alt="" style="cursor:pointer;" title="' + 'lang.resetSize' + '" />',
					'</div>',
					//align
					'<div class="ke-dialog-row">',
					'<label style="width:60px;">' + '位置' + '</label>',
					' <input type="radio" checked="checked" name="align" class="ke-inline-block" value="left"  checked="checked"/> <img name="leftImg" src="' + imgPath + 'align_left.gif" width="23" height="25" alt="" />',
					' <input type="radio" name="align" class="ke-inline-block" value="right" /> <img name="rightImg" src="' + imgPath + 'align_right.gif" width="23" height="25" alt="" />',
					'</div>',
					//title
					'<div class="ke-dialog-row">',
					'<label for="remoteTitle" style="width:60px;">' + '标题' + '</label>',
					'<input type="text" id="remoteTitle" class="ke-input-text" name="title" value="" style="width:200px;" />',
					'</div>',
				'</div>',
				//remote image - end
				
				
				//本地图片上传
				//local upload - start
				'<div class="tab2" style="display:none;">',
					'<iframe name="' + target + '" style="display:none;"></iframe>',
					'<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + K.addParam(uploadJson, 'dir=image') + '">',
					//file
					'<div class="ke-dialog-row">',
					hiddenElements.join(''),
					'<label style="width:60px;">' + '图片路径' + '</label>',
					'<input type="text" name="localUrl" class="ke-input-text" tabindex="-1" style="width:200px;" readonly="true" /> &nbsp;',
					'<input type="button" class="ke-upload-button" value="' + '浏览..' + '" />',
					'</div>',
					'</form>',
					//size
					'<div class="ke-dialog-row">',
					'<label for="remoteWidth" style="width:60px;">' + '大小' + '</label>',
					'宽' + ' <input type="text" id="remoteWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ',
					'高' + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ',
					'<img class="ke-refresh-btn" src="' + imgPath + 'refresh.png" width="16" height="16" alt="" style="cursor:pointer;" title="' + 'lang.resetSize' + '" />',
					'</div>',
					//align
					'<div class="ke-dialog-row">',
					'<label style="width:60px;">' + '位置' + '</label>',
					' <input checked="checked" type="radio" name="align" class="ke-inline-block" value="left"  checked="checked"/> <img name="leftImg" src="' + imgPath + 'align_left.gif" width="23" height="25" alt="" />',
					' <input type="radio" name="align" class="ke-inline-block" value="right" /> <img name="rightImg" src="' + imgPath + 'align_right.gif" width="23" height="25" alt="" />',
					'</div>',
					//title
					'<div class="ke-dialog-row">',
					'<label for="remoteTitle" style="width:60px;">' + '标题' + '</label>',
					'<input type="text" id="remoteTitle" class="ke-input-text" name="title" value="" style="width:200px;" />',
					'</div>',
				'</div>',
				//local upload - end
			'</div>'
		].join('');
		var dialogWidth = showLocal || allowFileManager ? 450 : 400,
			dialogHeight = showLocal && showRemote ? 300 : 250;
		var dialog = self.createDialog({
			name : name,
			width : dialogWidth,
			height : dialogHeight,
			title : self.lang(name),
			body : html,
			//确定
			yesBtn : {
				name : self.lang('yes'),
				click : function(e) {
					// Bugfix: http://code.google.com/p/kindeditor/issues/detail?id=319
					if (dialog.isLoading) {
						return;
					}
					
					//本地上传 insert local image
					if (showLocal && showRemote && tabs && tabs.selectedIndex === 1 || !showRemote) {
						if (uploadbutton.fileBox.val() == '') {
							alert(self.lang('pleaseSelectFile'));
							return;
						}
						//显示加载图片
						dialog.showLoading(self.lang('uploadLoading'));
							//uploadbutton.submit();//上传图片
						dialog.hideLoading();
						
						var data = {
							error: 0,
							url: 'http://sysu.teweijia.com//'+'/upload/qiniu/erp/test__1558324304883.jpg',
							message: '上传成功',
							title: '附件',
							width: '200',
							height: '200',
							border: '0',
							align: ''
						}
						if (data.error === 0) {
							var url = data.url;
							if (formatUploadUrl) {
								url = K.formatUrl(url, 'absolute');
							}
							if (self.afterUpload) {
								self.afterUpload.call(self, url, data, name);
							}
							if (!fillDescAfterUploadImage) {
								clickFn.call(self, url, data.title, data.width, data.height, data.border, data.align);
							} else {
								K(".ke-dialog-row #remoteUrl", div).val(url);
								K(".ke-tabs-li", div)[0].click();
								K(".ke-refresh-btn", div).click();
							}
						} else {
							alert(data.message);
						}

						localUrlBox.val('');
						
						return;
					}
					
					//网络图片 insert remote image
					var url = K.trim(urlBox.val()),
						width = widthBox.val(),
						height = heightBox.val(),
						title = titleBox.val(),
						align = '';
					alignBox.each(function() {
						if (this.checked) {
							align = this.value;
							return false;
						}
					});
					if (url == 'http://' || K.invalidUrl(url)) {
						alert(self.lang('invalidUrl'));
						urlBox[0].focus();
						return;
					}
					if (!/^\d*$/.test(width)) {
						alert(self.lang('invalidWidth'));
						widthBox[0].focus();
						return;
					}
					if (!/^\d*$/.test(height)) {
						alert(self.lang('invalidHeight'));
						heightBox[0].focus();
						return;
					}
					clickFn.call(self, url, title, width, height, 0, align);
				}
			},
			beforeRemove : function() {
				viewServerBtn.unbind();
				widthBox.unbind();
				heightBox.unbind();
				refreshBtn.unbind();
			}
		}),
		div = dialog.div;

		var urlBox = K('[name="url"]', div),
			localUrlBox = K('[name="localUrl"]', div),
			viewServerBtn = K('[name="viewServer"]', div),
			widthBox = K('.tab1 [name="width"]', div),
			heightBox = K('.tab1 [name="height"]', div),
			refreshBtn = K('.ke-refresh-btn', div),
			titleBox = K('.tab1 [name="title"]', div),
			alignBox = K('.tab1 [name="align"]', div);

		var tabs;
		if (showRemote && showLocal) {
			tabs = K.tabs({
				src : K('.tabs', div),
				afterSelect : function(i) {}
			});
			tabs.add({
				title : '网络图片',
				panel : K('.tab1', div)
			});
			tabs.add({
				title : '本地图片',
				panel : K('.tab2', div)
			});
			tabs.select(1);
		} else if (showRemote) {
			K('.tab2', div).show();
		} else if (showLocal) {
			K('.tab1', div).show();
		}

		var uploadbutton = K.uploadbutton({
			button : K('.ke-upload-button', div)[0],
			fieldName : filePostName,
			form : K('.ke-form', div),
			target : target,
			width: 60,
			afterUpload : function(data) {
				dialog.hideLoading();
				if (data.error === 0) {
					var url = data.url;
					if (formatUploadUrl) {
						url = K.formatUrl(url, 'absolute');
					}
					if (self.afterUpload) {
						self.afterUpload.call(self, url, data, name);
					}
					if (!fillDescAfterUploadImage) {
						clickFn.call(self, url, data.title, data.width, data.height, data.border, data.align);
					} else {
						K(".ke-dialog-row #remoteUrl", div).val(url);
						K(".ke-tabs-li", div)[0].click();
						K(".ke-refresh-btn", div).click();
					}
				} else {
					alert(data.message);
				}
			},
			afterError : function(html) {
				dialog.hideLoading();
				self.errorDialog(html);
			}
		});
		uploadbutton.fileBox.change(function(e) {
			localUrlBox.val(uploadbutton.fileBox.val());
		});
		if (allowFileManager) {
			viewServerBtn.click(function(e) {
				self.loadPlugin('filemanager', function() {
					self.plugin.filemanagerDialog({
						viewType : 'VIEW',
						dirName : 'image',
						clickFn : function(url, title) {
							if (self.dialogs.length > 1) {
								K('[name="url"]', div).val(url);
								if (self.afterSelectFile) {
									self.afterSelectFile.call(self, url);
								}
								self.hideDialog();
							}
						}
					});
				});
			});
		} else {
			viewServerBtn.hide();
		}
		var originalWidth = 0, originalHeight = 0;
		function setSize(width, height) {
			widthBox.val(width);
			heightBox.val(height);
			originalWidth = width;
			originalHeight = height;
		}
		refreshBtn.click(function(e) {
			var tempImg = K('<img src="' + urlBox.val() + '" />', document).css({
				position : 'absolute',
				visibility : 'hidden',
				top : 0,
				left : '-1000px'
			});
			tempImg.bind('load', function() {
				setSize(tempImg.width(), tempImg.height());
				tempImg.remove();
			});
			K(document.body).append(tempImg);
		});
		widthBox.change(function(e) {
			if (originalWidth > 0) {
				heightBox.val(Math.round(originalHeight / originalWidth * parseInt(this.value, 10)));
			}
		});
		heightBox.change(function(e) {
			if (originalHeight > 0) {
				widthBox.val(Math.round(originalWidth / originalHeight * parseInt(this.value, 10)));
			}
		});
		urlBox.val(options.imageUrl);
		setSize(options.imageWidth, options.imageHeight);
		titleBox.val(options.imageTitle);
		alignBox.each(function() {
			if (this.value === options.imageAlign) {
				this.checked = true;
				return false;
			}
		});
		if (showRemote && tabIndex === 0) {
			urlBox[0].focus();
			urlBox[0].select();
		}
		return dialog;
	};
	self.plugin.image = {
		edit : function() {
			var img = self.plugin.getSelectedImage();
			self.plugin.imageDialog({
				imageUrl : img ? img.attr('data-ke-src') : 'http://',
				imageWidth : img ? img.width() : '',
				imageHeight : img ? img.height() : '',
				imageTitle : img ? img.attr('title') : '',
				imageAlign : img ? img.attr('align') : '',
				showRemote : allowImageRemote,
				showLocal : allowImageUpload,
				tabIndex: img ? 0 : imageTabIndex,
				clickFn : function(url, title, width, height, border, align) {
					if (img) {
						img.attr('src', url);
						img.attr('data-ke-src', url);
						img.attr('width', width);
						img.attr('height', height);
						img.attr('title', title);
						img.attr('align', align);
						img.attr('alt', title);
					} else {
						self.exec('insertimage', url, title, width, height, border, align);
					}
					// Bugfix: [Firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hideDialog
					setTimeout(function() {
						self.hideDialog().focus();
					}, 0);
				}
			});
		},
		'delete' : function() {
			var target = self.plugin.getSelectedImage();
			if (target.parent().name == 'a') {
				target = target.parent();
			}
			target.remove();
			// [IE] 删除图片后立即点击图片按钮出错
			self.addBookmark();
		}
	};
	self.clickToolbar(name, self.plugin.image.edit);
});

页面初始化

<script type="text/javascript" src="../../js/qiniu/js/plupload.full.min.js"></script>
		<script type="text/javascript" src="../../js/qiniu/moxie.min.js"></script>
		<script type="text/javascript" src="../../js/qiniu/qiniu.min.js"></script>
		<link rel="stylesheet" href="../../lib/kindeditor/themes/default/default.css" />
		<link rel="stylesheet" href="../../lib/kindeditor/plugins/code/prettify.css" />
		<script charset="utf-8" src="../../lib/kindeditor/kindeditor-all.js"></script>
		<script charset="utf-8" src="../../lib/kindeditor/lang/zh-CN.js"></script>
		<script charset="utf-8" src="../../lib/kindeditor/plugins/code/prettify.js"></script>
<script>
    //上述 upload方法代码
    //...............
</script>
<script>
//KindEditor编辑器初始化
KindEditor.lang({
	diy_video: '图片'
	});
	var editor;
	KindEditor.ready(function(K) {
	editor = K.create('#editHtml', {
		width:'700px',
		height:'400px',
		resizeType : 1,
		filterMode:true,
		allowImageUpload : true,
		items : [
			'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
			'removeformat', 'plainpaste','|', 'justifyleft', 'justifycenter', 'justifyright',
			'quickformat', 'link', 'unlink', 'diy_video' , 'fullscreen']
	});
});
</script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值