kindeditor 富文本自动上传

/ 默认分类 / 0 条评论 / 86浏览

1. js paste监听,clipboard中html+file类型数据处理

e.originalEvent.preventDefault() + insertHtml

 /*<![CDATA[*/
        KindEditor.ready(function(K) {
            var editor = K.create('div[name="text"]', {
                uploadJson : '/php/default/upload_json.php',
                fileManagerJson : '/php/default/file_manager_json.php',
                dialogOffset : 0, //对话框距离页面顶部的位置,默认为0居中,
                allowFileManager : true,
                                //filterMode : false,
                items : ['source','formatblock', 'fontname', 'fontsize','forecolor','justifyleft', 'justifycenter', 'justifyright',
                    'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'bold', 'italic', 'underline',
                    'lineheight', 'removeformat','code', 'quote', 'plainpaste','image', 'table', 'hr', 'pagebreak','link', 'unlink',
                    'preview'
                ],
                afterChange : function() {
                    this.sync();
                },
                afterCreate: function () {
                    var editerDoc = this.edit.doc;
                    //监听粘贴事件, 包括右键粘贴和ctrl+v
                    $(editerDoc).bind('paste', function (e) {
                        var ele = e.originalEvent.clipboardData.items;
                        //e.originalEvent.preventDefault();
                        for (var i = 0; i < ele.length; ++i) {
                            //复核类型进行处理
                            if(ele[i].type==="text/html"){
                              e.originalEvent.preventDefault();
                              ele[i].getAsString(function(pstct){//data文件类型
                                if(pstct.indexOf('data:image') !== -1){
                                    editor.insertHtml(pstct.replace(/<\s?img[^>]*>/gi, ''));//复合text
                                    var imgReg = /<img[^>]+>/g;
                                    var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
                                    var arr = pstct.match(imgReg); 
                                    for(var i=0;i<arr.length;i++){
                                        var result=arr[i].match(srcReg)[1];
                                        if(result.indexOf("data:image") !== -1 ){
                                            var file = base64DataToImageFile(result);
                                            ajaxUpload(file, editor)
                                        }
                                    } 
                                }else{
                                    editor.insertHtml(pstct);
                                }
                              });
                            }
                            if (ele[i].type.indexOf('image/') !== -1) {//文件类型
                                e.originalEvent.preventDefault();
                                var file = ele[i].getAsFile();
                                ajaxUpload(file, editor);
                            }
                        }
                    });
                },                      
                themeType : "primary", //主题
                //错误处理 handler
                errorMsgHandler : function(message, type) {
                    try {
                        JDialog.msg({type:type, content:message, timer:2000});
                    } catch (Error) {
                        alert(message);
                    }
                }
            });
          });
          
        function ajaxUpload(file, editor){
            var formData = new FormData();
            formData.append("imgFile", file); //name,value
            //用jquery Ajax 上传二进制数据
            $.ajax({
                url: '/uploadImg',
                type: 'POST',
                data: formData,
                // 告诉jQuery不要去处理发送的数据
                processData: false,
                contentType: false,
                dataType: "json",
                beforeSend: function () {
                    //console.log("正在进行,请稍候");
                },
                success: function (responseStr) {
                    var src = responseStr.url;
                    var imgTag = "<img src='" + src + "' border='0'/>";
                    editor.insertHtml(imgTag);
                },
                error: function (responseStr) {
                    console.log("error");
                }
            });
        }
        
        function base64DataToImageFile(dataurl){
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], "test.jpg", {type:mime});
        }
        /*]]>*/

2. 后端上传接口

 @PostMapping(value = "uploadImg")
	@ResponseBody
    public String uploadImg(HttpServletRequest request, @RequestParam("imgFile") MultipartFile zipFile) {
    	String webRootPath=request.getServletContext().getRealPath("");
//		JSONObject jo=new JSONObject(param);
//		String binaryString = jo.getString("imgFile");
		Date date=new Date();
		String str = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
		String urlPath = "/uploads/image/"+str.substring(0,6)+"/"
				+ str.substring(6,8) + "/" +str+"_" + i++ + ".jpg";
		String path=webRootPath+urlPath;
		
//		ImageBinary.base64StringToImage(path, binaryString);
		File targetFile = new File(path);
		File fileParent = targetFile.getParentFile();  
		if(!fileParent.exists()){  
			fileParent.mkdirs();  
		}  
		try {
			targetFile.createNewFile();
		} catch (IOException e1) {
			e1.printStackTrace();
		}  
		try(FileOutputStream fileOutputStream = new FileOutputStream(targetFile)) {
			IOUtils.copy(zipFile.getInputStream(), fileOutputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		JSONObject res = new JSONObject();
		res.put("url", urlPath);
    	return res.toString();
    }

3.参考

https://blog.csdn.net/weixin_30735745/article/details/95501334