關於富文本編輯器jodit的使用和使用中遇到的問題

 

Jodit v.3使用純TypeScript編寫的優秀開源WYSIWYG編輯器,無需使用其他庫,是國外的一個開源富文本編輯器

我打算在項目中集成這個富文本編輯框.

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

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

已經可以正常使用,其中還有一些小的功能,比如選項的配置,安裝官方給出的一些指導:

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<DeliveryRiders>().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);
	}
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章