froala富文本編輯器與golang、beego,脫離ueditor苦海

一直用百度的ueditor,可是阿里雲這種"wo chuo"的雲上部署的beego做的服務,總是出現ueditor.all.min.js語法錯誤,清理瀏覽器緩存後又會好起來。本地調試也沒問題。反覆無常。

用froala也是因爲體驗了官方的demo,帶圖片的word直接粘貼,不像ueditor那樣需要word圖片轉存。

還有就是少了好多配置。什麼ueditor.config.js,config.json,還有什麼// 服務器統一請求接口路徑URL +, serverUrl:  "/controller",光寫這個controller就折騰你了,因爲golang語言它官方不提供啊。

Ueditor的bug主要有:插入的圖片沒法調整大小,插入的表格沒法調整大小,插入的圖片超出顯示範圍,插入視頻展示的時候css配置衝突,當然,這些網絡上都有解決辦法,但是糟心。

開始以爲froala也像ueditor那樣,有語言上的障礙,用後果然如別人說的,跟語言毫無關係,只有一個上傳圖片的服務就好了。

所以,早點脫離苦海吧。

1.上傳圖片(視頻和文件)

網絡上都是寫這個的,我開始納悶,難道這個編輯器只有這個嗎?用了後確實,就只要這個有了,然後,就沒有了,不用其他的了。

配置裏:

<script>
    // $(function(){
    //   $('#edit').froalaEditor()
    // });
$(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').froalaEditor({
      placeholderText: '請輸入內容',
      charCounterCount       : true,//默認
      // charCounterMax         : -1,//默認
      saveInterval            : 0,//不自動保存,默認10000
      // theme                    : "red",
      height                   : "300px",
      toolbarBottom           : false,//默認
      toolbarButtonsMD        : toolbarButtonsMD,
      toolbarButtonsSM        : toolbarButtonsSM,
      toolbarButtonsXS        : toolbarButtonsXS,
      toolbarInline           : false,//true選中設置樣式,默認false
      imageUploadMethod       : 'POST',
      heightMin: 450,
      charCounterMax: 3000,
      // imageUploadURL: "uploadImgEditor",
      imageParams: { postId: "123" },
      params: {
            acl: '01',
            AWSAccessKeyId: '02',
            policy: '03',
            signature: '04',
          },
      autosave: true,
      autosaveInterval: 2500,
      saveURL: 'hander/FroalaHandler.ashx',
      saveParams: { postId: '1'},
      spellcheck: false,
      imageUploadURL: '/uploadimg',//上傳到本地服務器
      imageUploadParams: {pid: '{{.Id}}'},
      imageDeleteURL: 'lib/delete_image.php',//刪除圖片
      imagesLoadURL: 'lib/load_images.php',//管理圖片
      enter: $.FroalaEditor.ENTER_BR,
      language: 'zh_cn',
      // toolbarButtons: ['bold', 'italic', 'underline', 'paragraphFormat', 'align','color','fontSize','insertImage','insertTable','undo', 'redo']
      });
    })
  </script>

其實只有一句重點,帶參數的圖片上傳,如下

imageUploadURL: '/uploadimg',//上傳到本地服務器
      imageUploadParams: {pid: '{{.Id}}'},

這樣服務端就取到圖片和pid參數了。

func (c *FroalaController) UploadImg() {
	//解析表單
	pid := c.Input().Get("pid")
	// beego.Info(pid)
	//pid轉成64爲
	pidNum, err := strconv.ParseInt(pid, 10, 64)
	if err != nil {
		beego.Error(err)
	}
	//根據proj的parentIdpath
	Url, DiskDirectory, err := GetUrlPath(pidNum)
	if err != nil {
		beego.Error(err)
	}
	beego.Info(DiskDirectory)
	//獲取上傳的文件
	_, h, err := c.GetFile("file")
	if err != nil {
		beego.Error(err)
	}
	// beego.Info(h.Filename)
	fileSuffix := path.Ext(h.Filename)
	// random_name
	newname := strconv.FormatInt(time.Now().UnixNano(), 10) + fileSuffix // + "_" + filename
	// err = ioutil.WriteFile(path1+newname+".jpg", ddd, 0666) //buffer輸出到jpg文件中(不做處理,直接寫到文件)
	// if err != nil {
	// 	beego.Error(err)
	// }
	year, month, _ := time.Now().Date()
	err = os.MkdirAll(DiskDirectory+"\\"+strconv.Itoa(year)+month.String()+"\\", 0777) //..代表本當前exe文件目錄的上級,.表示當前目錄,沒有.表示盤的根目錄
	if err != nil {
		beego.Error(err)
	}
	var path string
	var filesize int64
	if h != nil {
		//保存附件
		path = DiskDirectory + "\\" + strconv.Itoa(year) + month.String() + "\\" + newname
		Url = "/" + Url + "/" + strconv.Itoa(year) + month.String() + "/"
		err = c.SaveToFile("file", path) //.Join("attachment", attachment)) //存文件    WaterMark(path)    //給文件加水印
		if err != nil {
			beego.Error(err)
		}
		filesize, _ = FileSize(path)
		filesize = filesize / 1000.0
		c.Data["json"] = map[string]interface{}{"state": "SUCCESS", "link": Url + newname, "title": "111", "original": "demo.jpg"}
		c.ServeJSON()
	} else {
		c.Data["json"] = map[string]interface{}{"state": "ERROR", "link": "", "title": "", "original": ""}
		c.ServeJSON()
	}
}

服務端返回{‘link’:圖片的地址}就行了。

上傳視頻和文件的服務端可以一樣,但是頁面中要配置地址和參數。

imageUploadURL: '/uploadimg',//上傳到本地服務器
      imageUploadParams: {pid: '{{.Id}}'},
      imageDeleteURL: 'lib/delete_image.php',//刪除圖片
      imagesLoadURL: 'lib/load_images.php',//管理圖片
      videoUploadURL:'/uploadvideo',
      videoUploadParams: {pid: '{{.Id}}'},
      fileUploadURL: '/uploadimg',
      fileUploadParams: {pid: '{{.Id}}'},
插入的視頻地址功能,似乎只能支持youtu的視頻網站地址,你自己隨便搞個視頻地址是不行的。

2.文章顯示

官網有例子了。

<div class="fr-view">
              {{str2html .article.Content}}
            </div>

引入

<link rel="stylesheet" href="/static/froala/css/froala_style.css">

即可。比ueditor簡單吧。

3.文章內容獲得並提交服務端

function save2(){
var html = $('div#edit').froalaEditor('html.get');
$.ajax({
        type:"post",
url:"/project/product/addarticle",
        data: {content:html},
        success:function(data,status){
          alert("添加“"+data+"”成功!(status:"+status+".)");
        }, 
      });

var html = $('div#edit').froalaEditor('html.get');

就行了。

4.文章編輯

跟新建文章一樣。

或者,如果是form表單提交,可能是按下列方法。官方的Textarea Editor例子不知道是不是想表達這個意思。

<div id="editor">
  <h3>編輯文章</h3>
  <form  method="post" action="/project/product/updatearticle" enctype="multipart/form-data">
      <label>文章內容:</label>
        <textarea id='edit' style="margin-top: 30px;" placeholder="Type some text">
          {{str2html .article.Content}}
        </textarea>
        <br />
      <button type="submit" class="btn btn-primary" style="float:right">提交修改</button>
  </form>
</div>
//編輯器初始化並賦值 
  $('#edit')
  .on('froalaEditor.initialized', function (e, editor) {
        $('#edit').parents('form').on('submit', function () {
          // console.log($('#edit').val());
          var articleid = {{.article.Id}};
          var subtext = $('#subtext').val();
          $.ajax({
            type:"post",
            url:"/project/product/updatearticle",
            data: {aid:articleid,subtext:subtext,content:$('#edit').val()},
            success:function(data,status){
              alert("修改成功!");
              window.location.reload();//刷新頁面
            },
          });
          // return false;
        })
      })
  .froalaEditor({
      // enter: $.FroalaEditor.ENTER_P,
      placeholderText: '請輸入內容',
      charCounterCount       : true,//默認
      // charCounterMax         : -1,//默認
      saveInterval            : 0,//不自動保存,默認10000
      // theme                    : "red",
      height                   : "550px",
      toolbarBottom           : false,//默認
      toolbarButtonsMD        : toolbarButtonsMD,
      toolbarButtonsSM        : toolbarButtonsSM,
      toolbarButtonsXS        : toolbarButtonsXS,
      toolbarInline           : false,//true選中設置樣式,默認false
      imageUploadMethod       : 'POST',
      heightMin: 450,
      charCounterMax: 3000,
      // imageUploadURL: "uploadImgEditor",
      imageParams: { postId: "123" },
      params: {
            acl: '01',
            AWSAccessKeyId: '02',
            policy: '03',
            signature: '04',
          },
      autosave: true,
      autosaveInterval: 2500,
      saveURL: 'hander/FroalaHandler.ashx',
      saveParams: { postId: '1'},
      spellcheck: false,
      imageUploadURL: '/uploadimg',//上傳到本地服務器
      imageUploadParams: {pid: '{{.product.ProjectId}}'},
      imageDeleteURL: 'lib/delete_image.php',//刪除圖片
      imagesLoadURL: 'lib/load_images.php',//管理圖片
      enter: $.FroalaEditor.ENTER_BR,
      language: 'zh_cn',
      // toolbarButtons: ['bold', 'italic', 'underline', 'paragraphFormat', 'align','color','fontSize','insertImage','insertTable','undo', 'redo']
      });
    })

5.官方例子直接下載看

在github上下載的包,直接用瀏覽器打開index.html


一切都在,不過關於參數傳遞還真沒找到例子。

6.添加中文字體

它自己所帶的字體很少,但例子裏有font例子,自己對照着添加中文字體吧。不添加一般情況下似乎也沒啥影響。

7.模態框中的富文本編輯器

把froala放在模態框中,但是上傳圖片後,鼠標點擊圖片,不會彈出圖片操作窗口,因爲這個窗口的z-index值是5,而bootstrap模態框的z-index值是1045,需要在頁面的頭部加上style,模態框的id,z-index值設爲3

div#modalTable2 {/*.modal .fade .in*/
        z-index: 3;
      }
如果設置爲0,則激活的按鈕會蓋過模態框。

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