1. 程式人生 > >SpringBoot整合富文字編輯器(UEditor)

SpringBoot整合富文字編輯器(UEditor)

UEditro是一款比較好用的富文字編輯器,所謂的富文字編輯器就是和伺服器互動的資料不是普通的字串檔案,而是一些內容包含比較廣的字串,一般是指的html頁面,目前比較好用的是百度的UEditor,到官方網站下載:
http://ueditor.baidu.com/website/download.html
這裡寫圖片描述

1、首先在專案下新建ueditor資料夾,吧下載的ueditor檔案裡面的內容全部拷貝進去;
這裡寫圖片描述

2、在我們需要使用富文字編輯器的頁面裡面引入ueditor:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title
>
My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta
http-equiv="description" content="This is my page">
<script src="<%=path %>/ueditor/ueditor.config.js"></script> <script src="<%=path %>/ueditor/ueditor.all.min.js"></script> <script src="<%=path %>/ueditor/lang/zh-cn/zh-cn.js"></script> <script type="text/javascript"> var editor = UE.getEditor('container'); alert(editor); </script> </head> <body> <textarea id="container" name="content" type="text/plain">這裡寫你的初始化內容</textarea> </body> </html>

啟動程式,訪問效果如下:
這裡寫圖片描述

在index.jsp增加如下程式碼,將資料提交到伺服器:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">


    <script src="<%=path %>/ueditor/ueditor.config.js"></script>
    <script src="<%=path %>/ueditor/ueditor.all.min.js"></script>
    <script src="<%=path %>/ueditor/lang/zh-cn/zh-cn.js"></script>


        <script type="text/javascript">
           var editor = UE.getEditor('container');


           function postDate() {


           }

        </script>
  </head>

  <body>
    <form action="<%=path %>/news/addNews.do" method="post">
     <textarea id="container" name="content" type="text/plain">這裡寫你的初始化內容</textarea>
     <button id="btn" onclick="postDate()">提交</button>
    </form>

  </body>
</html>

controller寫法:

package com.xingxue.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/news")
public class NewsController {

    @RequestMapping("/addNews.do")
    public String addNews(String content) {

        System.out.println(content);
        return "ok";
    }
}

測試結果

這裡寫圖片描述

此時,我們伺服器已經能收到資料,就可以存入資料庫,或者生產靜態html檔案,

4、解決圖片問題:

先編寫好接收圖片的controller

package com.xingxue.controller;


import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;



import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/news")
public class NewsController {

    @RequestMapping("/addNews.do")
    public String addNews(String content) {

        System.out.println(content);
        return "ok";
    }


    @RequestMapping("/upload.do")
    @ResponseBody
    public Map<String, Object> images (MultipartFile upfile, HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> params = new HashMap<String, Object>();
        System.out.println("1111111111111");
        try{
            String basePath = "e:/img";  //與properties檔案中lyz.uploading.url相同,未讀取到檔案資料時為basePath賦預設值
            String  visitUrl = "/upload/"; //與properties檔案中lyz.visit.url相同,未讀取到檔案資料時為visitUrl賦預設值
             String ext = "abc" + upfile.getOriginalFilename();
             String fileName = String.valueOf(System.currentTimeMillis()).concat("_").concat(""+new Random().nextInt(6)).concat(".").concat(ext);
             StringBuilder sb = new StringBuilder();
             //拼接儲存路徑
             sb.append(basePath).append("/").append(fileName);
             visitUrl = visitUrl.concat(fileName);
             File f = new File(sb.toString());
             if(!f.exists()){
                 f.getParentFile().mkdirs();
             }
             OutputStream out = new FileOutputStream(f);
             FileCopyUtils.copy(upfile.getInputStream(), out);
             params.put("state", "SUCCESS");
             params.put("url", visitUrl);
             params.put("size", upfile.getSize());
             params.put("original", fileName);
             params.put("type", upfile.getContentType());
        } catch (Exception e){
             params.put("state", "ERROR");
        }
         return params;
    }

}

該接收圖片有幾個細節:
第一: MultipartFile upfile 引數名必須和我們ueditro配置檔名字一樣:
這裡寫圖片描述

返回資料型別不能錯誤:
這裡寫圖片描述

state:上傳圖片的狀態
url:訪問圖片的路徑

ueditro配置檔案修改:
這裡寫圖片描述

更改jspdiamante:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">


    <script src="<%=path %>/ueditor/ueditor.config.js"></script>
    <script src="<%=path %>/ueditor/ueditor.all.min.js"></script>
    <script src="<%=path %>/ueditor/lang/zh-cn/zh-cn.js"></script>


        <script type="text/javascript">
           var editor = UE.getEditor('container');

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

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

                if(action == '/news/upload.do'){
                    return '/news/upload.do';
                }else{
                    return this._bkGetActionUrl.call(this, action);
                }

            }


        </script>
  </head>

  <body>
    <form action="<%=path %>/news/addNews.do" method="post">
     <textarea id="container" name="content" type="text/plain">這裡寫你的初始化內容</textarea>
     <button id="btn" onclick="postDate()">提交</button>
    </form>

  </body>
</html>

注意:
return ‘/news/upload.do’; //ssm要帶專案名, springboot不需要帶專案名

測試效果:
這裡寫圖片描述

注意:圖片的路徑我們可以用一個虛擬的圖片伺服器來模擬,需要修改controller的程式碼

package com.xingxue.controller;


import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;



import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/news")
public class NewsController {

    @RequestMapping("/addNews.do")
    public String addNews(String content) {

        System.out.println(content);
        return "ok";
    }


    @RequestMapping("/upload.do")
    @ResponseBody
    public Map<String, Object> images (MultipartFile upfile, HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> params = new HashMap<String, Object>();
        System.out.println("1111111111111");
        try{
            String basePath = "e:/img";  //與properties檔案中lyz.uploading.url相同,未讀取到檔案資料時為basePath賦預設值
             String ext = "abc" + upfile.getOriginalFilename();
             String fileName = String.valueOf(System.currentTimeMillis()).concat("_").concat(""+new Random().nextInt(6)).concat(".").concat(ext);
             StringBuilder sb = new StringBuilder();
             //拼接儲存路徑
             sb.append(basePath).append("/").append(fileName);
             //寫到e盤
             File f = new File(sb.toString());
             if(!f.exists()){
                 f.getParentFile().mkdirs();
             }
             OutputStream out = new FileOutputStream(f);
             FileCopyUtils.copy(upfile.getInputStream(), out);


             //虛擬圖片伺服器
             String  visitUrl = "http://localhost:9999/ssm/"; 
             visitUrl = visitUrl.concat(fileName);
             f = new File("D:/server/project/ssm/" + fileName);
              out = new FileOutputStream(f);
             FileCopyUtils.copy(upfile.getInputStream(), out);


             params.put("state", "SUCCESS");
             params.put("url", visitUrl);
             params.put("size", upfile.getSize());
             params.put("original", fileName);
             params.put("type", upfile.getContentType());
        } catch (Exception e){
            e.printStackTrace();
             params.put("state", "ERROR");
        }
         return params;
    }

}