kindeditor 跨域上传图片配置 富文本编辑

字数 117阅读 6406

本文用于解决kindeditor跨域上传配置,服务端上传接口使用java。
kindeditor 调用服务端上传接口需要返回如下json数据

//成功时
{
        "error" : 0,
        "url" : "http://www.example.com/path/to/file.ext"
}
//失败时
{
        "error" : 1,
        "message" : "错误信息"
}

一、先创建一个redirect.html,放于kindeditor项目目录下

这个文件用于解决跨域,跟使用富文本编辑的页面放入同项目

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>ie </title>
    <script type="text/javascript">
    function getParameter(val) {
        var uri = decodeURI(window.location.search);
        var re = new RegExp("" + val + "=([^&?]*)", "ig");
        return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1)) : null);
    }

        var upload_callback = function() {
            var error = getParameter("error");
            error = parseInt(error)
            var dataObject;
            if(error==0){
                var url = getParameter("url");
                dataObject = {"error": error, "url": url};
            }else{
                var message = getParameter("message");
                dataObject = {"error": error, "message": message};
            }
            var data =  JSON.stringify(dataObject)
            document.getElementsByTagName("body")[0].innerHTML = '<pre>' + data + '</pre>';
        }
    </script>
</head>
<body onload="upload_callback();">
</body>
</html>

二、页面调用kindeditor代码部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form id="form1" runat="server">
    <script charset="utf-8" src="../node_modules/kindeditor/kindeditor-all.js"
            type="text/javascript"></script>
    <script type="text/javascript" charset="utf-8">
var callBackPath = 'xxx/redirect.html';//redirect.html的请求路径 例如 http://www.abc.com/redirect.html
KindEditor.ready(function(K) {
            editor = K.create('#txtContent', {
                filePostName: 'file',//跟服务端参数对应
                allowFileManager: true,
                uploadJson: 'XXX/common/kindEditorUpload?callBackPath='+callBackPath,
                items : [ 'source', 'image']
            });
        });

    </script>
    <textarea cols="60" id="txtContent" style="width: 600px; height: 300px;" runat="server"
              readonly="readonly"></textarea>
</form>
</body>
</html>

三、 服务端接口代码( java 上传部分为伪代码)

@RequestMapping(value = "/common/kindEditorUpload", method = RequestMethod.POST)
    public String uploadKindEditor( @RequestParam String callBackPath, 
                            @RequestBody MultipartFile file){
                //filePath为绝对路径
        String filePath = FileUtils.upload(file);
        String url = "";
        try {
            // 同域时直接返回json,跨域需redirect
            url = "redirect:" + callBackPath + "?error=0&url="filePath;
        } catch (Exception e) {
            e.printStackTrace();
            url = "redirect:" + callBackPath + "?error=1&message="+"错误信息";
        }
        return url;
    }