1. 程式人生 > >froala富文本編輯器與golang、beego,脫離ueditor苦海

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

success Edito insert ike alert css nan ued gin

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

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

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

開始以為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’:圖片的地址}就行了。

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

技術分享圖片

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

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