富文本使用之wangEditor3

1、介紹:

wangEditor —— 輕量級 web 富文本編輯器,配置方便,使用簡單。支持 IE10+ 瀏覽器。javascript

2、使用方式:

3、使用:

重點是圖片的上傳和富文本內容的獲取。css

1.圖片上傳:html

①存放在一個臨時的文件夾裏。java

②將圖片地址返給前臺,富文本顯示圖片。jquery

2.內容獲取:git

①獲取富文本的內容,截取內容裏的圖片標籤。github

②將圖片存入到一個新的文件夾裏,替換圖片的地址。web

③將新的富文本的內容存儲到數據庫裏。(這裏我未做處理)ajax

前臺代碼:數據庫

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>富文本的使用</title>
    <style type="text/css">
        body {
            width: 800px;
            margin: 0 auto 0 auto;
        }
    </style>
</head>
<body>

<!--wangEditor 使用 B-->
<div id="div1">
</div>
<!--wangEditor 使用 E-->
<button id="addBtn" onclick="addNews()">增長</button>

</body>
<script type="text/javascript" src="../release/wangEditor.js"></script>
<script src="js/jquery-3.2.1.js"></script>
<script type="text/javascript">
    var httpurl = "http://localhost:8081";

    //富文本使用
    var E = window.wangEditor;
    var editor = new E('#div1');
    //從新設置富文本的內容
    editor.customConfig.menus = [
        'head',  // 標題
        'bold',  // 粗體
        'fontSize',  // 字號
        'italic',  // 斜體
        'underline',  // 下劃線
        'foreColor',  // 文字顏色
        'link',  // 插入連接
        'justify',  // 對齊方式
        'image',  // 插入圖片
        'undo',  // 撤銷
        'redo'  // 重複
    ];
    // 隱藏「網絡圖片」tab
    editor.customConfig.showLinkImg = false;
    // 將圖片大小限制爲 3M
    editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
    // 限制一次最多上傳 1 張圖片
    editor.customConfig.uploadImgMaxLength = 1;
    //開啓wangEditor的錯誤提示
    editor.customConfig.debug=true;
    // 關閉粘貼樣式的過濾
    editor.customConfig.pasteFilterStyle = false;
    // 忽略粘貼內容中的圖片
    editor.customConfig.pasteIgnoreImg = true;


    //上傳圖片 將圖片以文件的形式傳給後臺進行操做返回圖片 url
    editor.customConfig.customUploadImg = function (files, insert) {
        var date = new FormData();
        date.append("file", files[0]);
        $.ajax({
            type: "POST",
            url: httpurl + "/test/upload",
            data: date,
            dataType: 'json',
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (result) {
                insert(result.data);// insert 是獲取圖片 url 後,插入到編輯器的方法
            }
        })
    };
    editor.create();//建立富文本

    /**
     * 添加企業新聞
     */
    function addNews() {
        var formData = new FormData();
        formData.append("news",editor.txt.html());
        $.ajax({
            type: "POST",
            url: httpurl + "/test/addNews",
            data: formData,
            dataType: 'json',
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (result) {
                console.log(result);
            }
        })
    }
</script>
</html>

後臺代碼:

/**
 * 圖片上傳
 * @param request
 * @param file
 * @return
 */
public JSONObject upload(HttpServletRequest request,MultipartFile file) {
    JSONObject imgPathObject = new JSONObject();
    Map map = new HashMap();
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    List<FileItem> list = null  ;
    if(isMultipart){
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");

        try {

            //獲取文件名(帶後綴名)
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //企業新聞id
            String entNewsImgId = UUIDUtil.getOneUUID();
            fileName = entNewsImgId + suffixName;


            //獲取文件輸入流
            InputStream input = file.getInputStream();

            // 獲取當前時間
            String format = DateUtil.DEF_DATE_FORMAT_STR;
            String strDate = DateUtil.dateToString(new Date(),format);
            String StrDateTime = strDate.substring(0, 10);

            //獲取工程路徑
            String serverAddress = request.getServletContext().getRealPath("/");
            String entNewsImgPath = serverAddress +"tempRes/busiPic/" + StrDateTime +"/" + fileName;
            int result = writeToLocal(entNewsImgPath, input);
            String imgPath = "http://localhost:8081/tempRes/busiPic/" + StrDateTime +"/" + fileName;
            if(result == 1) {
                map.put("data", imgPath);
                String  entNewsStr = JSONObject.toJSONString(map);
                imgPathObject = JSONObject.parseObject(entNewsStr);

            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    return imgPathObject;
}

/**
 * 將InputStream寫入本地文件
 * @param filePath 寫入本地目錄
 * @param input 輸入流
 * @throws IOException
 */
private static int writeToLocal(String filePath, InputStream input)  {
    //定義每次讀取的長度
    int index = -1;
    //定義每次讀取字節的大小與保存字節的數據
    byte[] bytes = new byte[1024];
    FileOutputStream downloadFile;
    try {
        //保證建立一個新文件
        File file = new File(filePath);
        if (!file.getParentFile().exists()) { // 若是父目錄不存在,建立父目錄
            file.getParentFile().mkdirs();
        }
        file.createNewFile();

        downloadFile = new FileOutputStream(filePath);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return 0;
    } catch (IOException e) {
        e.printStackTrace();
        return 0;
    }
    return 1;
}

/**
 * 獲取富文本內容
 * @param request
 * @param file
 * @return
 */
public JSONObject addNews(HttpServletRequest request, MultipartFile file) {
    Map map = new HashMap();
    //新聞的UUID
    String entNewsId = UUIDUtil.getOneUUID();
    String newsCon = "";//新的新聞內容
    String newsImgPath = "";//新聞圖片路徑
    String newsContent = request.getParameter("news");//獲取新聞內容
    System.out.println(newsContent);
    //截取圖片路徑
    String tempSrc= "<img src=\"";
    String[] imgStr = newsContent.split(tempSrc);
    String[] imgPathStr = new String[imgStr.length];//圖片路徑數組
    System.out.println(imgStr.length);
    if(imgStr.length > 1) {
        String[] imgLengthStr = imgStr[1].split("\"");
        int imgLength = imgLengthStr[0].length();

        for (int i=1; i< imgStr.length; i++) {
            newsImgPath = imgStr[i].substring(0,imgLength);
            System.out.println(newsImgPath);
            //改變圖片路徑
            String tempPort = "8081/";
            String tempImgPath = request.getServletContext().getRealPath("/") + newsImgPath.split(tempPort)[1];
            String tempImgUUID = newsImgPath.substring(newsImgPath.lastIndexOf("/")+1);
            System.out.println(tempImgPath);
            String imgPathNewAbove = request.getServletContext().getRealPath("/");
            String imgPathNewBehind ="busiPic/entNewsPic/"+ entNewsId +"/pic_" + tempImgUUID;
            String imgPathNew = imgPathNewAbove + imgPathNewBehind;
            File oldFile = new File(tempImgPath);
            File newFile = new File(imgPathNew);
            Boolean bln = copyFile(oldFile,newFile);
            if(bln)
                imgPathStr[i-1] = newsImgPath.split(tempPort)[0] + tempPort + imgPathNewBehind;
        }
        
        newsCon = imgStr[0];
        for (int i=1; i< imgStr.length; i++) {
            newsCon += tempSrc + imgPathStr[i-1] + imgStr[i].substring(imgLength);
        }
        System.out.print(newsCon);
        map.put("newsContent",newsCon);

    }else {
        map.put("newsContent",newsContent);
    }
    String  newContentStr = JSONObject.toJSONString(map);
    JSONObject result = JSONObject.parseObject(newContentStr);
    return result;
}

/**
 * 複製文件
 * @param source
 * @param dest
 * @throws IOException
 */
public static boolean copyFile(File source, File dest){

    //保證建立一個新文件
    if (!dest.getParentFile().exists()) { // 若是父目錄不存在,建立父目錄
        dest.getParentFile().mkdirs();
    }
    if (dest.exists()) { // 若是已存在,刪除舊文件
        dest.delete();
    }
    InputStream input = null;
    OutputStream output = null;
    try {
        dest.createNewFile();//建立文件
        input = new FileInputStream(source);
        output = new FileOutputStream(dest);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buf))>-1) {
            output.write(buf, 0, bytesRead);
        }
        output.close();
        input.close();
    }catch (IOException e) {
        e.printStackTrace();
    }catch(Exception e){
        e.printStackTrace();
        return false;
    }
    return true;
}

樣式如圖:

相關文章
相關標籤/搜索