原理: 监听粘贴事件(paste) 获取粘贴版数据,读取到图片数据流进行加载base64 传到后台服务端直接输出为图片文件保存后返回图片读取路径插入编辑器中
/** * 获取编辑器对象 */ window.$KindEditor = KindEditor.create('#submit_editor', { width : $("#submit_editor").width(), height: $("#submit_editor").height(), cssPath : contextPath + "/static/plugin/kindeditor/plugins/code/prettify.css", uploadJson : contextPath + "/static/plugin/kindeditor/jsp/upload_json.jsp", fileManagerJson : contextPath + "/static/plugin/kindeditor/jsp/file_manager_json.jsp", allowFileManager : true, resizeType:0,//2或1或0,2时可以拖动改变宽度和高度,1时只能改变高度,0时不能拖动 afterBlur:function(){ $KindEditor.sync("#submit_editor"); }, afterCreate:function(){ var doc = this.edit.doc; var cmd = this.edit.cmd; $(doc.body).bind('paste',function(ev){ var $this = $(this); var dataItem = ev.originalEvent.clipboardData.items[0]; if(dataItem){ var file = dataItem.getAsFile(); if(file){ var reader = new FileReader(); reader.onload = function(evt) { var imageDataBase64 = evt.target.result; $.post(contextPath + "/imgUpload/base64.action",{"imageDataBase64":imageDataBase64},function(resp){ var respData = resp; if(respData.errCode == 0){ var html = '<img src="' + respData.result + '" alt="" />'; cmd.inserthtml(html); } }); }; reader.readAsDataURL(file); } } }); } }); window.prettyPrint();
package com.innopro.sp.controller; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import sun.misc.BASE64Decoder; import com.busp.common.base.exception.ErrorCode; import com.busp.common.base.model.ResultVo; import com.busp.common.util.string.StringUtil; import com.innopro.sp.common.Constants; /** * @ClassName: LoginController * @version 2.0 * @Desc: 图片上传控制器 * @date 2017年5月23日上午10:47:43 * @history v2.0 * */ @Controller public class ImageUploadController extends BaseController{ private Logger logger = Logger.getLogger(ImageUploadController.class); public final String IMAGETYPES = "gif,jpg,jpeg,png,bmp"; /** * 描述:kindeditor 粘贴图片上传 * @author Jack * @date 2017年5月23日上午11:04:16 * @return */ @RequestMapping(value = "/imgUpload/base64", method = RequestMethod.POST) public void imageUploadBase64(HttpServletResponse response) { @SuppressWarnings("unchecked") ResultVo<String> resultVo = ResultVo.getInance(); try{ String imgageFilePath = null; String imageDataBase64 = getRequest().getParameter("imageDataBase64"); if(!StringUtil.isEmpty(imageDataBase64)){ String[] arrImageData = imageDataBase64.split(","); String[] arrTypes = arrImageData[0].split(";"); String[] arrImageType = arrTypes[0].split(":"); String imageType = arrImageType[1]; String imageTypeSuffix = imageType.split("/")[1]; if("base64".equalsIgnoreCase(arrTypes[1])&&this.IMAGETYPES.indexOf(imageTypeSuffix.toLowerCase())!=-1){ BASE64Decoder decoder = new BASE64Decoder(); byte[] decodeBuffer = decoder.decodeBuffer(arrImageData[1]); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); String currFormat = df.format(new Date()); File currFileBag = new File(Constants.ATTACHED_PATH +currFormat); if(!currFileBag.exists()){ currFileBag.mkdirs(); } imgageFilePath = currFormat+"/"+new Random().nextInt(100000) + "." + imageTypeSuffix; File currFile = new File(Constants.ATTACHED_PATH +imgageFilePath); int i = 0; while(currFile.exists()){ imgageFilePath = currFormat+"/"+new Random().nextInt(100000) + "." + imageTypeSuffix; currFile = new File(Constants.ATTACHED_PATH +imgageFilePath); i++; if(i>=100000){ imgageFilePath = null; currFile = null; break; } } if(currFile!=null){ OutputStream out = new FileOutputStream(currFile); out.write(decodeBuffer); out.flush(); out.close(); } } } //imgageFilePath路径存在表示上传成功 if(imgageFilePath!=null){ resultVo.setResult(Constants.ATTACHED_URL +imgageFilePath); }else{ logger.error("上传图片发生未知异常...."); resultVo.setErrCode(ErrorCode.SYS_ERROR_COMMON_CODE); resultVo.setErrMsg(ErrorCode.SYS_ERROR_COMMON_MSG); } }catch(Exception e){ logger.error("上传图片发生异常: ", e); resultVo.setErrCode(ErrorCode.SYS_ERROR_COMMON_CODE); resultVo.setErrMsg(ErrorCode.SYS_ERROR_COMMON_MSG); } outJSONData(resultVo,response); } }
Constants.ATTACHED_URL :项目访问图片路径
Constants.ATTACHED_PATH :图片保存路径