超好用的富文字編輯器froalaEditor(方便傳圖片和視訊等)
最近專案有個文章管理功能,我對比了很多富文字編輯器,有的是上傳圖片不方便,有的是複製貼上不方便,有的是但編輯器裡面不能改變圖片大小,最後,我找到了froalaEditor,可以說是集各種功能為一身,不但介面清爽,功能也十分全面,插入圖片和視訊都很方便,自己可以到官網體驗一下:https://www.froala.com/wysiwyg-editor
由於官方提供的下載包沒有第三方外掛,不太全,所以自己整理了全面的外掛
外掛下載地址:
程式碼:
<!DOCTYPE HTML> <html> <head> <!-- Include external CSS. --> <link href="${ctx }/common/static/froala_editor_2.8.5/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="${ctx }/common/static/froala_editor_2.8.5/codemirror/codemirror-5.40.2/lib/codemirror.css"> <link href="${ctx }/common/static/froala_editor_2.8.5/css/themes/dark.min.css" rel="stylesheet" type="text/css" /> <!-- Include Editor style. --> <link href="${ctx }/common/static/froala_editor_2.8.5/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" /> <link href="${ctx }/common/static/froala_editor_2.8.5/css/froala_style.min.css" rel="stylesheet" type="text/css" /> <title>建立文章</title> </head> <body> <article class="page-container" style="margin-left:25px;"> <input type="hidden" name="articleId" id="articleId" value="${article.article_id}"/> <div class="row cl" > <div id="artcleName"> <input type="text" class="input-text" placeholder="輸入文章標題" style="background:#eee;margin-bottom:10px;"> </div> <div id="edit"> </div> </div> <div class="row cl" style="margin:50px 0;"> <div class="col-xs-8 col-sm-7 col-xs-offset-4 col-sm-offset-3"> <input class="btn btn-primary radius" type="button" onclick="saveArticle()" value=" 提交 "> </div> </div> </article> <script type="text/javascript" src="${ctx}/common/lib/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="${ctx}/common/lib/layer/2.4/layer.js"></script> <script type="text/javascript" src="${ctx }/common/static/froala_editor_2.8.5/codemirror/codemirror-5.40.2/lib/codemirror.js"></script> <script type="text/javascript" src="${ctx }/common/static/froala_editor_2.8.5/codemirror/codemirror-5.40.2/mode/xml/xml.js"></script> <!-- Include Editor JS files. --> <script type="text/javascript" src="${ctx }/common/static/froala_editor_2.8.5/js/froala_editor.pkgd.min.js"></script> <!--中文字型包,注意要放在最下面,不然會報錯--> <script type="text/javascript" src="${ctx }/common/static/froala_editor_2.8.5/js/languages/zh_cn.js"></script> <script type="text/javascript"> $(function (){ //超大螢幕的功能按鈕 var toolbarButtons = ['fullscreen', 'bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript', 'fontFamily', 'fontSize', '|', 'color', 'emoticons', 'inlineStyle', 'paragraphStyle', '|', 'paragraphFormat', 'align', 'formatOL', 'formatUL', 'outdent', 'indent', 'quote', 'insertHR', '-', 'insertLink', 'insertImage', 'insertVideo', 'insertFile', 'insertTable', 'undo', 'redo', 'clearFormatting', 'selectAll', 'html']; //大螢幕的功能按鈕 var toolbarButtonsMD = ['fullscreen', 'bold', 'italic', 'underline', 'fontFamily', 'fontSize', 'color', 'paragraphStyle', 'paragraphFormat', 'align', 'formatOL', 'formatUL', 'outdent', 'indent', 'quote', 'insertHR', 'insertLink', 'insertImage', 'insertVideo', 'insertFile', 'insertTable', 'undo', 'redo', 'clearFormatting']; //小螢幕的功能按鈕 var toolbarButtonsSM = ['fullscreen', 'bold', 'italic', 'underline', 'fontFamily', 'fontSize', 'insertLink', 'insertImage', 'insertTable', 'undo', 'redo']; //手機的功能按鈕 var toolbarButtonsXS = ['bold', 'italic', 'fontFamily', 'fontSize', 'undo', 'redo']; //var pid = $('#pid').val(); //編輯器初始化並賦值 $('#edit').on('froalaEditor.initialized', function (e, editor) { $('#edit').froalaEditor('html.set','${article.article_content}'); }) .froalaEditor({ placeholderText: '請輸入內容', //預設填充內容 charCounterCount : true,//預設 顯示字數 saveInterval : 0,//不自動儲存,預設10000,0為不自動儲存 //theme : "dark",//主題:dark,red,gray,royal,注意需要引入對應主題的css height : "600px", toolbarBottom : false,//預設 toolbarButtonsMD : toolbarButtonsMD, toolbarButtonsSM : toolbarButtonsSM, toolbarButtonsXS : toolbarButtonsXS, toolbarInline : false,//true選中設定樣式,預設false imageUploadMethod : 'POST', heightMin: 450, charCounterMax: 3000, //最大字數限制,-1為不限制 saveURL: '${ctx}/webmana/article/saveArticle', //自動儲存的地址(body引數為html內容) saveParams: { postId: '1'}, //儲存內容時傳的引數 spellcheck: false, //是否允許瀏覽器對輸入內容進行拼寫檢查 imageUploadURL: '${ctx}/webmana/attachment/uploadArticleImg',//上傳到本地伺服器 //imageUploadParams: {pid: '1'}, //上傳圖片時帶的引數 ///imageDefaultWidth: 100, //上傳圖片後的預設大小 //imageResizeWithPercent: true,//不設定這個,imageDefaultWidth的單位為畫素,設定後為% videoUploadURL:'${ctx}/webmana/attachment/uploadArticleVideo', enter: $.FroalaEditor.ENTER_BR, //設定回車鍵功能 language: 'zh_cn', // toolbarButtons: ['bold', 'italic', 'underline', 'paragraphFormat', 'align','color','fontSize','insertImage','insertTable','undo', 'redo'] }); }) function saveArticle(){ var html=$('#edit').froalaEditor('html.get', true); //返回富文字編輯裡面的html程式碼 $.ajax({ type: 'POST', url: '${ctx}/webmana/article/saveArticle', dataType: 'json', data:{ "articleName":$("#articleName").val(), "body":html, "articleId":$("#articleId").val() }, success: function(data){ if(data.success){ layer.msg("儲存成功", {icon: 1, time: 1500},function(){ window.parent.location.reload(); }); }else{ layer.msg("儲存失敗", {icon: 1, time: 1500},function(){ window.parent.location.reload(); }); } }, error:function(data) { //console.log(data.msg); }, }); } </script> </body>
程式碼裡面比較說的比較清楚了,外掛預設按鈕是英文title,引入中文包並設定就成為中文了,下面先總結幾個比較重要的點
1.初始化:
$('#edit').froalaEditor({})
2.自動儲存:
saveURL為自動儲存地址,如果需要就設定為點選儲存相同的地址即可
3.儲存時傳入引數
saveParams: { postId: '1'} 在這個引數中可以放入儲存文章時順帶往後臺傳的引數
4.圖片上傳路徑
imageUploadURL 如果要圖片上傳功能,則這個路徑必須寫,路徑為儲存圖片的路徑,上傳圖片時的引數在imageUploadParams中寫。
注意:後臺儲存圖片需要返回給前臺圖片的路徑,而且格式必須是這樣的
附java後臺上傳圖片方法:
// 上傳文章圖片 @RequestMapping(value = "uploadArticleImg", method = RequestMethod.POST, produces = "application/json;charset=utf-8") @ResponseBody public String uploadArticleImg( @RequestParam(value = "file") MultipartFile file, //這樣接收檔案 @RequestParam Map<String,String> params, HttpServletRequest request ) { Map<String,Object> ret=new HashMap<String, Object>(); try { String path="/attachments/articleImages/"; Map<String,String> name=uploadFile(path,file, request); ret.put("link","http://" + request.getServerName() //伺服器地址 + ":" + request.getServerPort() +path+name.get("saveName")); // 返回前臺 return JSON.toJSONString(ret); } catch (Exception e) { e.printStackTrace(); return JSON.toJSONString("fail"); } } public Map<String,String> uploadFile(String path,MultipartFile file, HttpServletRequest request) throws IOException { Map<String,String> result=new HashMap<String,String>(); String fileName = file.getOriginalFilename(); //String basePath=request.getSession().getServletContext().getRealPath("/"); // path=basePath+path; //設定檔案儲存路徑 // File tempFile = new File(path, new Date().getTime() + String.valueOf(fileName)); String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase(); String saveName=String.valueOf((new Date()).getTime()).substring(8)+(int)((Math.random()*999+1))+'.'+fileType; File tempFile = new File(basePath+path, String.valueOf(saveName)); if (!tempFile.getParentFile().exists()) { //建立資料夾 tempFile.getParentFile().mkdir(); } if (!tempFile.exists()) { tempFile.createNewFile(); } file.transferTo(tempFile); result.put("fileName",fileName); result.put("saveName",saveName); return result; }
5.視訊上傳
videoUploadURL在這個引數中寫視訊的上傳路徑,方法與上傳圖片相同
6.獲取編輯完成生成的程式碼:
var html=$('#edit').froalaEditor('html.get', true); //返回富文字編輯裡面的html程式碼
提交時就把這個html提交後臺即可,獲取的文字是有行內樣式的html標籤,如下,如果要展示文章,直接將html賦值給一個div就可以完全復原
標題<br><img src="http://localhost:8081/attachments/articleImages/47321141.jpg" style="width: 515px;" class="fr-fic fr-dib"><br><span class="fr-video fr-dvb fr-draggable" contenteditable="false" draggable="true"><video class="fr-draggable fr-fvc fr-dvi" controls="" src="http://localhost:8081/attachments/articleVideos/23907698.mp4" style="width: 1145px; height: 522px;">Your browser does not support HTML5 video.</video></span>
7.點選編輯按鈕時將舊資料放進編輯中
$('#edit').on('froalaEditor.initialized', function (e, editor) {
$('#edit').froalaEditor('html.set','獲取的html文字');
})
.froalaEditor({})
加一個'froalaEditor.initialized',在裡面用$('#edit').froalaEditor('html.set','獲取的html文字') 即可
8.手機端展示最好把上傳的圖片視訊預設為寬度100%
一般圖片上傳後會將你調整後的圖片寬度以px為單位存入後臺,但是有時我們需要圖片寬度為100%,則需要設定
imageDefaultWidth和imageResizeWithPercent:true引數
不設定imageResizeWithPercent,imageDefaultWidth的單位為畫素,設定後為%
9.破解
注意,因為此編輯器有個版權問題,在本機自己練習時正常,但程式部署到伺服器時使用編輯時,會在編輯器內出現一行紅色背景的字,提醒你版權問題,影響使用者體驗
解決辦法:
.fr-wrapper > div[style*='z-index: 9999'] {
position: absolute;
top: -10000px;
opacity: 0;
display: none;
}
在使用頁加上上述css就行了,版權提醒去無蹤
*僅限個人學習使用,商用的話還是購買下版權吧