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

 

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

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

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

//开始使用
通过 bower安装
bower install jodit
通过 npm安装
npm install jodit
CDN使用方法


Self-hosted · Download files


使用:
html:
js: var editor = new Jodit('#editor'); jquery: $('textarea').each(function () { var editor = new Jodit(this); editor.value = '

start

'; });

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

uploadimage,filebrowser
var editor = new Jodit('#editor', {
    uploader: {
        url: 'http://localhost:8181/index-test.php?action=fileUpload'
    },
    filebrowser: {
        ajax: {
            url: 'http://localhost:8181/index-test.php'
        }
    }
});
Create plugin
Jodit.plugins.yourplugin = function (editor) {
    editor.events.on('afterInit', function () {
        editor.seleciotn.insertHTMl('Text');
    });
}
Add custom button
var editor = new Jodit('.someselector', {
    extraButtons: [
        {
            name: 'insertDate',
            iconURL: 'http://xdsoft.net/jodit/logo.png',
            exec: function (editor) {
                editor.selection.insertHTML((new Date).toDateString());
            }
        }
    ]
})

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

uploader: {
    url: 'http://localhost:8181/index-test.php?action=fileUpload'
},

修改为

uploader: {
    url: "/articlesLife/admin/uploadAboutMePic",
    insertImageAsBase64URI: false,
    imagesExtensions: [
			    "jpg",
			    "png",
			    "jpeg",
			    "gif"
			  ],
    //headers: {"token":`${db.token}`},
    filesVariableName: 'files',
    withCredentials: false,
    pathVariableName: "path",
    format: "json",
    method: "POST",
    prepareData: function (formdata) {
        file = formdata.getAll("files[0]")[0];
        //formdata.append("createTime", (Date.now() / 1000) | 0);
        formdata.append("aboutMePic", file);
        return formdata;
    },
    isSuccess: function (e) {
        console.log(e);
        //console.log("shuju"+e.length);
        return e.data;
    },
    getMessage: function (e) {
        return void 0 !== e.data.messages && Array.isArray(e.data.messages) ? e.data.messages.join("") : ""
    },
    process: function (resp) {
        var ss = this;
        console.log(resp);
        var arrfile = [];
        //arrfile.push(resp.data);
        arrfile.unshift(resp.data);
        console.log(arrfile.length + "" + arrfile[0]);
        //this.selection.insertImage(arrfile[0]);
        return {
            files: arrfile, //[this.options.uploader.filesVariableName] || [],
            path: '',
            baseurl: '',
            error: resp.msg,
            msg: resp.msg
        };
        //return resp.data;
    },
    error: function (e) {
        this.jodit.events.fire("errorMessage", e.message, "error", 4e3)
    },
    defaultHandlerSuccess: function (resp) {},
    defaultHandlerError: function (e) {
        this.jodit.events.fire("errorMessage", e.message)
    },
    contentType: function (e) {
        return (void 0 === this.jodit.ownerWindow.FormData || "string" == typeof e) &&
            "application/x-www-form-urlencoded; charset=UTF-8"
    }
}

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

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

后台使用springboot

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

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

process: function (resp) {
        var ss = this;
        console.log(resp);
        var arrfile = [];
        //arrfile.push(resp.data);
        arrfile.unshift(resp.data);
        console.log(arrfile.length + "" + arrfile[0]);
        //this.selection.insertImage(arrfile[0]);
        return {
            files: arrfile, //[this.options.uploader.filesVariableName] || [],
            path: '',
            baseurl: '',
            error: resp.msg,
            msg: resp.msg
        };
        //return resp.data;
    },

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":`${db.token}`},
        filesVariableName: function(t){return "files["+t+"]"},//"files",
        withCredentials: false,
        pathVariableName: "path",
        format: "json",
        method: "POST",
        prepareData: function (formdata) {
            file = formdata.getAll("files[0]")[0];
            //formdata.append("createTime", (Date.now() / 1000) | 0);
            formdata.append("aboutMePic", file);
            return formdata;
        },
        isSuccess: function (e) {
            console.log(e);
            //console.log("shuju"+e.length);
            return e.data;
        },
        getMessage: function (e) {
            return void 0 !== e.data.messages && Array.isArray(e.data.messages) ? e.data.messages.join("") : ""
        },
        process: function (resp) {
            var ss = this;
            console.log(resp);
            var arrfile = [];
            arrfile.unshift(resp.data);
            console.log(arrfile.length + "||路径:" + arrfile[0]);
            console.log("再次打印:"+resp.data+"||baseurl:");
            return {
                files: arrfile, //[this.options.uploader.filesVariableName] || [],
                path: '',
                baseurl: '',
                error: resp.msg,
                msg: resp.msg,
                isImages:arrfile,
            };
            //return resp.data;
        },
        error: function (e) {
            this.jodit.events.fire("errorMessage", e.message, "error", 4e3)
        },
        defaultHandlerError: function (e) {
            this.jodit.events.fire("errorMessage", e.message)
        },
        contentType: function (e) {
            return (void 0 === this.jodit.ownerWindow.FormData || "string" == typeof e) &&
                "application/x-www-form-urlencoded; charset=UTF-8"
        }
      },
      filebrowser: {
        ajax: {
            url: 'https://xdsoft.net/jodit/connector/index.php'
        }
      }
    });
@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 = ClassUtils.getDefaultClassLoader().getResource("").getPath();
		//String path = ResourceUtils.getURL("classpath:").getPath();
		String filePath = "http://127.0.0.1:8090/uploadFile/userpic/";//request.getServletContext().getRealPath("/")/ridersFile/userpic/
//本地的路径存储上传文件的地方,后面要做地址的映射
		String localpath="/Volumes/MacFile/myWorkSpace/File/aboutUs/pic/";//System.getProperty("user.dir")+"/src/main/resources/static/uploadFile";
		// 存放在这个路径下:该路径是该工程目录下的static文件下:(注:该文件可能需要自己创建)
		// 放在static下的原因是,存放的是静态文件资源,即通过浏览器输入本地服务器地址,加文件名时是可以访问到的
		//String localpath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/";
		//String filename=System.currentTimeMillis()+"";
		//TODO 判断文件格式是不是图片
        String contentType = multipartFile.getContentType();
        int index=contentType.indexOf('/');
        String fileType=contentType.substring(index+1);
        System.out.println("获取上传的文件名:"+multipartFile.getOriginalFilename()+"文件的类型:"+fileType);
        //byte[] imagebyte=Base64ImageUtils.base64ToByte(base64str, filePath, filename);
        System.out.println("pngjpgjpegJPGPNGJPEG".contains(fileType));
        String picUrl=null;
        if("pngjpgjpegJPGPNGJPEG".contains(fileType)) {
        	String originalFileName="aboutMe"+FileNameUtils.getFileName(multipartFile.getOriginalFilename());
			File tmpFile = new File(localpath);
			//判断是否存在该文件夹,若不存在则创建文件夹
			if(!tmpFile.exists()){
				tmpFile.mkdir();
			}
			File file = new File(localpath, originalFileName);
	        //String fileName = file.toString();
	      //for(MultipartFile file:files){
	        try {
				multipartFile.transferTo(file);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        //if(Base64ImageUtils.imgsaveToFile(imagebyte, fileName)) {
			//for(MultipartFile file:files){
			//files.transferTo(new File(filePath+files.getOriginalFilename()));
	        System.out.println(originalFileName);
	        System.out.println(file.getAbsolutePath());
	        picUrl=filePath+originalFileName;
			}
			// if(deliveryRidersService.addPerfectRder(riders)>0) {
			// 	return Result.success(true);
			// }
	        // }else {
	        // 	return Result.error("文件格式不是图片!");
	        // }
//			if(deliveryRidersService.getOne(new QueryWrapper().eq("phone", riders.getPhone())) != null) {
//				return Result.error(ResultEnum.USER_IS_EXISTS.getCode(),ResultEnum.USER_IS_EXISTS.getMsg());
//			}else if(deliveryRidersService.addPerfectRder(riders)>0){
//				//int flag=deliveryRidersService.riderRegister(deliveryRiders);
//				return Result.success(true);
//			}
        //}else {
        	//MyException exception=new MyException("文件类型错误!");
    		//return Result.error("文件类型错误!");
        //}
        //MyException exception=new MyException("没有完成!发生异常!");
		return Result.success(picUrl);
	}
}

 

 

你可能感兴趣的:(javascript,jquery,jodit,editor,jodit,editor,富文本编辑器)