关于富文本编辑器jodit的使用和使用中遇到的问题

时间:2025-01-31 11:08:22

 

Jodit v.3使用纯TypeScript编写的优秀开源WYSIWYG编辑器,无需使用其他库,是国外的一个开源富文本编辑器

我打算在项目中集成这个富文本编辑框.

按照官网的教程基本配置成功!

//开始使用
通过 bower安装
bower install jodit
通过 npm安装
npm install jodit
CDN使用方法
<link rel="stylesheet" href="///ajax/libs/jodit/3.1.39/">
<script src="///ajax/libs/jodit/3.1.39/"></script>
Self-hosted · Download files
<link rel="stylesheet" href="build/">
<script src="build/"></script>
使用:
html:<textarea  name="editor"></textarea>或<div ></div>
js:
var editor = new Jodit('#editor');
jquery:
$('textarea').each(function () {
    var editor = new Jodit(this);
     = '<p>start</p>';
});

已经可以正常使用,其中还有一些小的功能,比如选项的配置,安装官方给出的一些指导:

uploadimage,filebrowser
var editor = new Jodit('#editor', {
    uploader: {
        url: 'http://localhost:8181/?action=fileUpload'
    },
    filebrowser: {
        ajax: {
            url: 'http://localhost:8181/'
        }
    }
});
Create plugin
 = function (editor) {
    ('afterInit', function () {
        ('Text');
    });
}
Add custom button
var editor = new Jodit('.someselector', {
    extraButtons: [
        {
            name: 'insertDate',
            iconURL: '/jodit/',
            exec: function (editor) {
                ((new Date).toDateString());
            }
        }
    ]
})

其中图片上传默认是以base64编码的形式存储的,这样的话,在一边文档中有许多图片,就会使得文档变大,不利于存储及显示,我们要改成路径存储在文档中,根据上面的代码

uploader: {
    url: 'http://localhost:8181/?action=fileUpload'
},

修改为

uploader: {
    url: "/articlesLife/admin/uploadAboutMePic",
    insertImageAsBase64URI: false,
    imagesExtensions: [
			    "jpg",
			    "png",
			    "jpeg",
			    "gif"
			  ],
    //headers: {"token":`${}`},
    filesVariableName: 'files',
    withCredentials: false,
    pathVariableName: "path",
    format: "json",
    method: "POST",
    prepareData: function (formdata) {
        file = ("files[0]")[0];
        //("createTime", (() / 1000) | 0);
        ("aboutMePic", file);
        return formdata;
    },
    isSuccess: function (e) {
        (e);
        //("shuju"+);
        return ;
    },
    getMessage: function (e) {
        return void 0 !==  && () ? ("") : ""
    },
    process: function (resp) {
        var ss = this;
        (resp);
        var arrfile = [];
        //();
        ();
        ( + "" + arrfile[0]);
        //(arrfile[0]);
        return {
            files: arrfile, //[] || [],
            path: '',
            baseurl: '',
            error: ,
            msg: 
        };
        //return ;
    },
    error: function (e) {
        ("errorMessage", , "error", 4e3)
    },
    defaultHandlerSuccess: function (resp) {},
    defaultHandlerError: function (e) {
        ("errorMessage", )
    },
    contentType: function (e) {
        return (void 0 ===  || "string" == typeof e) &&
            "application/x-www-form-urlencoded; charset=UTF-8"
    }
}

其中url为上传图片的接口;

prepareData: function (formdata) {
        file = ("files[0]")[0];
        //("createTime", (() / 1000) | 0);
        ("aboutMePic", file);
        return formdata;
},这一段为上传的参数名称及图片,aboutMePic为上传图片的参数名,

后台使用springboot

public Result uploadAboutMePic(@RequestParam("aboutMePic") MultipartFile multipartFile, HttpServletRequest request,HttpServletResponse response) {}

isSuccess:中为上传成功返回的参数;根据自己定义的返回参数结构来解析;

process: function (resp) {
        var ss = this;
        (resp);
        var arrfile = [];
        //();
        ();
        ( + "" + arrfile[0]);
        //(arrfile[0]);
        return {
            files: arrfile, //[] || [],
            path: '',
            baseurl: '',
            error: ,
            msg:
        };
        //return ;
    },

process:中的这个很重要,是上传成功之后返回图片的路径插入到富文本框中,我的返回数据格式是 {code:"1000",msg:"成功",data:"上传成功返回的图片路径",count:""}

其中files为图片路径的数组集合,把一次上传图片返回的图片路径存入数组,其实一次上传只有一个图片,所以数组中只有一张图片资源,path:和baseurl:我没用到,我所使用的就是以上的方法,上传成功后返回图片路径,并插入在文本框中!

下面看我完整的配置代码:

//jodit富文本编辑器
    var joditor = new Jodit('#jodit_editor',{
        zIndex: 10,
      language: 'zh_cn',
        width:'auto',
      height: 500,
        minHeight: 500,
        toolbarStickyOffset: 100,
        saveModeInCookie: false,
        iframeStyle: '*,.jodit_wysiwyg {color:red;}',
        observer: {
            timeout: 800
        },
      uploader: {
        url: "/articlesLife/admin/uploadAboutMePic",
        insertImageAsBase64URI: false,
        imagesExtensions: [
              "jpg",
              "png",
              "jpeg",
              "gif"
            ],
        //headers: {"token":`${}`},
        filesVariableName: function(t){return "files["+t+"]"},//"files",
        withCredentials: false,
        pathVariableName: "path",
        format: "json",
        method: "POST",
        prepareData: function (formdata) {
            file = ("files[0]")[0];
            //("createTime", (() / 1000) | 0);
            ("aboutMePic", file);
            return formdata;
        },
        isSuccess: function (e) {
            (e);
            //("shuju"+);
            return ;
        },
        getMessage: function (e) {
            return void 0 !==  && () ? ("") : ""
        },
        process: function (resp) {
            var ss = this;
            (resp);
            var arrfile = [];
            ();
            ( + "||路径:" + arrfile[0]);
            ("再次打印:"++"||baseurl:");
            return {
                files: arrfile, //[] || [],
                path: '',
                baseurl: '',
                error: ,
                msg: ,
                isImages:arrfile,
            };
            //return ;
        },
        error: function (e) {
            ("errorMessage", , "error", 4e3)
        },
        defaultHandlerError: function (e) {
            ("errorMessage", )
        },
        contentType: function (e) {
            return (void 0 ===  || "string" == typeof e) &&
                "application/x-www-form-urlencoded; charset=UTF-8"
        }
      },
      filebrowser: {
        ajax: {
            url: '/jodit/connector/'
        }
      }
    });
@RequestMapping("/articlesLife")
public class ArticlesLifeController {
	@RequestMapping("/admin/uploadAboutMePic")
	public Result uploadAboutMePic(@RequestParam("aboutMePic") MultipartFile multipartFile, HttpServletRequest request,HttpServletResponse response) {
		//ArticlesLife aboutUs=new ArticlesLife();
		//String path = ().getResource("").getPath();
		//String path = ("classpath:").getPath();
		String filePath = "http://127.0.0.1:8090/uploadFile/userpic/";//().getRealPath("/")/ridersFile/userpic/
//本地的路径存储上传文件的地方,后面要做地址的映射
		String localpath="/Volumes/MacFile/myWorkSpace/File/aboutUs/pic/";//("")+"/src/main/resources/static/uploadFile";
		// 存放在这个路径下:该路径是该工程目录下的static文件下:(注:该文件可能需要自己创建)
		// 放在static下的原因是,存放的是静态文件资源,即通过浏览器输入本地服务器地址,加文件名时是可以访问到的
		//String localpath = ().getResource("").getPath()+"static/";
		//String filename=()+"";
		//TODO 判断文件格式是不是图片
        String contentType = ();
        int index=('/');
        String fileType=(index+1);
        ("获取上传的文件名:"+()+"文件的类型:"+fileType);
        //byte[] imagebyte=Base64ImageUtils.base64ToByte(base64str, filePath, filename);
        ("pngjpgjpegJPGPNGJPEG".contains(fileType));
        String picUrl=null;
        if("pngjpgjpegJPGPNGJPEG".contains(fileType)) {
        	String originalFileName="aboutMe"+(());
			File tmpFile = new File(localpath);
			//判断是否存在该文件夹,若不存在则创建文件夹
			if(!()){
				();
			}
			File file = new File(localpath, originalFileName);
	        //String fileName = ();
	      //for(MultipartFile file:files){
	        try {
				(file);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				();
			}
	        //if((imagebyte, fileName)) {
			//for(MultipartFile file:files){
			//(new File(filePath+()));
	        (originalFileName);
	        (());
	        picUrl=filePath+originalFileName;
			}
			// if((riders)>0) {
			// 	return (true);
			// }
	        // }else {
	        // 	return ("文件格式不是图片!");
	        // }
//			if((new QueryWrapper<DeliveryRiders>().eq("phone", ())) != null) {
//				return (ResultEnum.USER_IS_EXISTS.getCode(),ResultEnum.USER_IS_EXISTS.getMsg());
//			}else if((riders)>0){
//				//int flag=(deliveryRiders);
//				return (true);
//			}
        //}else {
        	//MyException exception=new MyException("文件类型错误!");
    		//return ("文件类型错误!");
        //}
        //MyException exception=new MyException("没有完成!发生异常!");
		return (picUrl);
	}
}

 

 

相关文章