1. 程式人生 > >百度ueditor的圖片上傳,前後端交互使用

百度ueditor的圖片上傳,前後端交互使用

插件 request 刪掉 rem con inner 頁面 prefix 文件目錄

百度ueditor的使用

  一個文本編輯器,看了網上很多文檔寫的很亂,這裏拾人牙慧,整理下怎麽使用。

這個東西如果不涉及到圖片附件上傳,其實很簡單,就是幾個前端文件,直接引用,然後配置下ueditor.config.js即可。這裏就不多說。

至於圖片上傳,ueditor 設計的時候是考慮和後端交互的,所以會看到可以下載什麽php,java版本,還有很多網上會說道有什麽後端配置文件,改那改這的,但是實際上後端存儲業務是按照公司實際來的,實踐起來並不順利。

本文重點講述的只用前端文件和ueditor.all.js、ueditor.config.js,如果來實踐和後端交互,圖片上傳。

(步驟1)下載文件,文件目錄如下,圖中的php (java、net)刪掉,我們不需要提供的後端文件。主要會調整到ueditor.all.js,ueditor.config.js

技術分享圖片

(步驟2) 然後參考官網 在頁面放如下的html和js引用,如下。這是頁面就能顯示編輯器了,工具欄的內容在ueditor.config.js的toolbars配置

<!DOCTYPE HTML> <html lang="en-US"> 
<head> <meta charset="UTF-8">
  <title>ueditor demo</title>
</head>
<body> <!-- 加載編輯器的容器 -->
<script id="container" name="content" type="text/plain"> 這裏寫你的初始化內容 </script> <!-- 配置文件 -->
<script type="text/javascript" src="ueditor.config.js"></script> <!-- 編輯器源碼文件 -->
<script type="text/javascript" src="ueditor.all.js"></script> <!-- 實例化編輯器 -->
<script type="text/javascript"> var
ue = UE.getEditor(‘container‘); </script> </body> </html>

保存和修改,就通過js獲取編輯器的內容,再ajax請求或form表單了。

//獲取html內容,返回: <p>hello</p> 

var html = ue.getContent();
var html = ue.setContent(); 

//獲取純文本內容,返回: hello

var txt = ue.getContentTxt();

(步驟3) 後端交互(重點)

  到這裏,如果還想圖片文件上傳,就會遇到一個問題,瀏覽器會報錯,顯示

ueditor 後端配置項沒有正常加載,上傳插件不能正常使用。這個是因為ueditor加載後,會去請求後端,拿後端的配置項。

  我們還沒處理後端邏輯,自然會報錯。

  ueditor給我們提供了一個請求URL配置,唯一和後端交互的地址,所有向後端的請求只有這個。就是ueditor.config.js裏面的serverUrl。

  但是如果我們有多個請求action事務呢,ueditor本身的設計是我們可以通過 http://serverUrl?action=actionA/actiongB. 在後端自己去分發action,上面的加載後端配置,請求就是=//serverUrl?action=config。

  我們按照這個思路來寫後端,也可以在前端轉發請求給不同的後端接口。下面講下這2種如何實現

1、通過唯一serverUrl接口,在後端分發aciton

先在ueditor.config.js配置下面參數

serverUrl:/ueditorEdit/eventHandler //唯一和後端交互的接口地址

imageActionName: /uploadimage //配置上傳圖片的action,沒有配置的話,有默認值uploadimage

在後端函數eventHandler裏,根據request的action參數做分發。

組件默認有哪些action,具體action的情況可以參考ueditor.all.js源碼 8006行,源碼如下

/**
         * 根據action名稱獲取請求的路徑
         * @method  getActionUrl
         * @remind 假如沒有設置serverUrl,會根據imageUrl設置默認的controller路徑
         * @param { String } action action名稱
         * @example
         * ```javascript
         * editor.getActionUrl(‘config‘); //返回 "/ueditor/php/controller.php?action=config"
         * editor.getActionUrl(‘image‘); //返回 "/ueditor/php/controller.php?action=uplaodimage"
         * editor.getActionUrl(‘scrawl‘); //返回 "/ueditor/php/controller.php?action=uplaodscrawl"
         * editor.getActionUrl(‘imageManager‘); //返回 "/ueditor/php/controller.php?action=listimage"
         * ```
         */
        getActionUrl: function(action){
            var actionName = this.getOpt(action) || action,
                imageUrl = this.getOpt(‘imageUrl‘),
                serverUrl = this.getOpt(‘serverUrl‘);

            if(!serverUrl && imageUrl) {
                serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, ‘$1controller$2‘);
            }

            if(serverUrl) {
                serverUrl = serverUrl + (serverUrl.indexOf(‘?‘) == -1 ? ‘?‘:‘&‘) + ‘action=‘ + (actionName || ‘‘);
                return utils.formatUrl(serverUrl);
            } else {
                return ‘‘;
            }
        }

  在後端eventHandler,接收到請求的aciton=config 時,就是獲取後端配置。由於我們並沒有使用後端配置,所以這裏返回了 {state:”配置文件初始化失敗“},如下圖,這樣改就能解決前端報後端配置項沒有正常加載的問題當然這裏你可以自己封裝返回結果(基本各自的框架都會對結果進行封裝),只要前端相應修改。java後端代碼如下

@RequestMapping("/eventHandler")

public void eventHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {

  //action==config加載後端配置處理

  if(request.getParameter("action").equals("config")){

    request.setCharacterEncoding( "utf-8" );

    response.setHeader("Content-Type" , "text/html");
  
    // 返回 {state: "配置文件初始化失敗"}

    //這裏沒有用ueditor的後端jar和後端配置,上傳的接口都是另外寫的。只需ueditor的前端文件即可

    //如果要使用ueditor的後端配置,需要把後端配置文件放到tomcat的根目錄或者指定目錄

    // 加載後端配置文件的js是ueditor.all.js的UE.Editor.prototype.loadServerConfig,可以直接在前端禁掉js加載後端配置的請求

    response.getWriter().write("{\"state\": \"\\u914d\\u7f6e\\u6587\\u4ef6\\u521d\\u59cb\\u5316\\u5931\\u8d25\"}");

  }

}

返回後,ueditor前端怎麽處理呢,可以看下在ueditor.all.js 8088行的源碼,如下。

       configUrl && UE.ajax.request(configUrl,{
                    ‘method‘: ‘GET‘,
                    ‘dataType‘: isJsonp ? ‘jsonp‘:‘‘,
                    ‘onsuccess‘:function(r){
                        try {
                            var config = isJsonp ? r:eval("("+r.responseText+")");
                            utils.extend(me.options, config);
                            me.fireEvent(‘serverConfigLoaded‘);
                            me._serverConfigLoaded = true;
                        } catch (e) {
                            showErrorMsg(me.getLang(‘loadconfigFormatError‘));
                        }
                    },
                    ‘onerror‘:function(){
                        showErrorMsg(me.getLang(‘loadconfigHttpError‘));
                    }
                });

解決完配置加載問題後,至於圖片上傳,就在eventHandler裏面判斷action=uploadimage 裏面自己去處理上傳邏輯,前端返回處理在ueditor.all.js 的24520,根據自己返回的結果調整下js腳本,如下,調整過的腳本

try{
                        var link, json, loader,
                            body = (iframe.contentDocument || iframe.contentWindow.document).body,
                            result = body.innerText || body.textContent || ‘‘;
                        json = (new Function("return " + result))();
                        //link = me.options.imageUrlPrefix + json.url;
                        //if(json.state == ‘SUCCESS‘ && json.url) {
                        //    loader = me.document.getElementById(loadingId);
                        //    loader.setAttribute(‘src‘, link);
                        //    loader.setAttribute(‘_src‘, link);
                        //    loader.setAttribute(‘title‘, json.title || ‘‘);
                        //    loader.setAttribute(‘alt‘, json.original || ‘‘);
                        //    loader.removeAttribute(‘id‘);
                        //    domUtils.removeClasses(loader, ‘loadingclass‘);
                        //} else {
                        //    showErrorLoader && showErrorLoader(json.state);
                        //}
                        if(json.success && json.result){
                            loader = me.document.getElementById(loadingId);
                            loader.setAttribute(‘src‘, json.result);
                            loader.setAttribute(‘_src‘, json.result);
                            loader.setAttribute(‘title‘, json.title || ‘‘);
                            loader.setAttribute(‘alt‘, json.original || ‘‘);
                            loader.removeAttribute(‘id‘);
                            domUtils.removeClasses(loader, ‘loadingclass‘);
                        }else{
                            showErrorLoader && showErrorLoader(json.success);
                        }
                    }catch(er){
                        showErrorLoader && showErrorLoader(me.getLang(‘simpleupload.loadError‘));
                    }

2、通過不同的接口對應不同的action

ueditor.config.js配置如下

serverUrl: "/xxx/loadConfig" //加載配置,後端返回失敗

imageActionName:"/xxx/uploadImage" //上傳圖片,前端轉發

然後我們把唯一的接口serverUrl當成加載配置的接口,上面的代碼中就不需要判斷action=config了,直接返回{state:”配置文件初始化失敗“},即可。

@RequestMapping("/eventHandler")

public void eventHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {

  request.setCharacterEncoding( "utf-8" );

  response.setHeader("Content-Type" , "text/html");

  response.getWriter().write("{\"state\": \"\\u914d\\u7f6e\\u6587\\u4ef6\\u521d\\u59cb\\u5316\\u5931\\u8d25\"}");

}

最後在前端轉發圖片上傳接口,在我們引用ueditor組件的前端頁面上,重寫UE.Editor.prototype.getActionUrl 函數,函數源碼在ueditor.all.js,可以自己去看. 重寫轉發如下,如果action=/xxx/uploadImage,直接請求/xxx/uploadImage

<script>

var ue = UE.getEditor(‘editor‘);

UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;

UE.Editor.prototype.getActionUrl =function(action){

//如果ation =圖片上傳,直接調用圖片上傳的接口

if(action == ‘/xxx/uploadImage‘){

  return ‘/xxx/uploadImage‘;

}else {

  return this._bkGetActionUrl.call(this,action);

}

};

</script>

這樣圖片上傳就會直接調用/xxx/uploadImage接口,而不影響serverUrl配置,圖片上傳後返回,也是在ueditor.all.js 的24525行進行調整

總結,這篇文章重在說明前後端交互調整的思路,具體如何實現,要按照自己的實際情況來使用。後端具體的存儲業務看各自的處理方式,但是我們要做的就是保存物理文件,拿回物理文件的地址。

百度ueditor的圖片上傳,前後端交互使用