BootStrap富文本編輯器Summernote

Summernote 是一個簡單靈活的所見即所得的 HTML 在線編輯器,基於JQuery 和 Bootstrap 構建,支持快捷鍵操作,提供大量可定製的選項。

官方API和插件下載

官網地址:http://summernote.org/getting-started/

下載地址:https://github.com/summernote/summernote/

效果圖

上傳圖片

調整圖片大小,對齊方式

文本輸入與顯示

Summernote基本使用

引入對應的樣式文件

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet"> 
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet"> 
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>

頁面只需要給一個textarea標籤,之後用JS渲染富文本編輯器,可以在textarea標籤中設置默認內容。

<textarea id="summernote" class="summernote"></textarea>

通過JS渲染及設置富文本編輯器的屬性。

$(function() {
    $('#summernote').summernote({
        height: 400,    //設置高度
        toolbar: [      //自定義工具欄
            ['style',['style']],
            ['font',['bold','underline','clear']],
            ['fontname',['fontname']],
            ['color',['color']],
            ['para',['ul','ol','paragraph', 'height', 'hr']],
            ['table',['table']],
            ['insert',['link','picture','video']],
            ['view',['fullscreen','codeview','help']]
        ],
        tabsize : 2,
        lang : 'zh-CN',
        callbacks : {     // 回調函數
            // 圖片上傳
            onImageUpload: function(files) {
                var formData = new FormData();
                formData.append("file", files[0]);
                $.ajax({
                    url: 'textEdit/imgUpload', //後臺文件上傳接口
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        //圖片插入到summernote中
                        $("#summernote").summernote('insertImage', data);
                    },
                    error: function () {
                        alert("上傳失敗")
                    }
                })
            },
            //清除word複製的格式
            onPaste: function (ne) {
                var bufferText = ((ne.originalEvent || ne).clipboardData || window.clipboardData).getData('Text/plain');
                ne.preventDefault ? ne.preventDefault() : (ne.returnValue = false);
                setTimeout(function () {
                    document.execCommand("insertText", false, bufferText);
                }, 10);
            }
        }
    });
});

toolbar設置工具欄功能控件,可以自定義,也可以使用默認的。

Summernote工具欄所有屬性。

  • 插入
    • picture: 打開圖像對話框
    • link: 打開鏈接對話框
    • video: 打開視頻對話框
    • table: 插入表格
    • hr: 插入水平線
  • 字體樣式
    • fontname: 設置字體系列
    • fontsize: 設置字體大小
    • color: 設置前景色和背景色
    • forecolor: 設置前景色
    • backcolor: 設置背景色
    • bold: 切換字體粗細
    • italic: 斜體
    • underline: 切換下劃線
    • strikethrough: 切換刪除線
    • superscript: 切換上標
    • subscript: 切換下標
    • clear: 清除字體樣式
  • 段落樣式
    • style: 格式化所選塊
    • ol: 切換有序列表
    • ul: 切換無序列表
    • paragraph: 段落對齊下拉菜單
    • height: 設置行高
  • 雜項
    • fullscreen: 切換全屏編輯模式
    • codeview: 切換所見即所得和html編輯模式
    • undo: 撤消
    • redo: 重做
    • help: 打開幫助對話框

onImageUpload覆蓋圖片上傳處理屬性,默認會把圖片轉換爲Base64格式,onImageUpload中可以設置用AJAX請求上傳圖片到本地。

後臺圖片上傳imgUpload()方法,代碼如下。

/**
 * 圖片上傳
 * @param file
 * @return
 */
@RequestMapping(value = "/imgUpload")
@ResponseBody
private Object imgUpload(MultipartFile file) {
    String uuid = UUID.randomUUID().toString()+".jpg";
    fileService.saveFile(file, uuid);
    return "http://localhost:8080/bootstrap/textEdit/download?uuid="+uuid;
}

/**
 * 圖片下載
 * @param uuid
 * @param request
 * @param response
 */
@RequestMapping(value = "/download")
@ResponseBody
private void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
    fileService.download(uuid, request, response);
}

上傳成功返回下載地址,用於圖片回顯。

saveFile上傳方法,download圖片下載方法。代碼如下。

// 圖片存放位置
private final static String IMAGEPATH="E:\\bootstrap\\image";

//保存圖片
@Transactional
public boolean saveFile(MultipartFile file, String uuid){
    try{
        File path = path(file.getContentType());
        String filename = file.getOriginalFilename();
        SysFile fileEntity = new SysFile();
        fileEntity.setFileName(filename);
        fileEntity.setUuid(uuid);
        String storeaddress = path.getAbsolutePath();
        fileEntity.setStoreaddress(storeaddress);
        File saveFile = new File(path,uuid);
        try {
            fileRepository.save(fileEntity);
            file.transferTo(saveFile);
            return true;
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return false;
        }
    }catch (Exception e){
        System.out.println("圖片保存異常");
        return false;
    }
}

//圖片地址是否存在
private File path(String filename) {
    File pat=new File("E:\\bootstrap");
    File path=new File(SysFileService.IMAGEPATH);
    if(!pat.isDirectory()) {
        pat.mkdir();
    }
    if(!path.isDirectory()) {
        path.mkdir();
    }
    return path;
}

/**
 * 下載
 * @param uuid
 * @param request
 * @param response
 */
public void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
    SysFile fileentity = fileRepository.findByUuid(uuid);
    String filename = fileentity.getFileName();
    filename = getStr(request, filename);
    File file = new File(fileentity.getStoreaddress(), uuid);
    if(file.exists()) {
        FileInputStream fis;
        try {
            fis = new FileInputStream(file);
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; filename=" + filename );
            ServletOutputStream out = response.getOutputStream();
            byte[] buf = new byte[2048];
            int n = 0;
            while((n = fis.read(buf))!=-1){
                out.write(buf, 0, n);
            }
            fis.close();
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private String getStr(HttpServletRequest request, String fileName) {
    String downloadFileName = null;
    String agent = request.getHeader("USER-AGENT");
    try {
        if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
            //downloadFileName = "=?UTF-8?B?" + (new String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?=";
            //設置字符集
            downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?=";
        }else{
            downloadFileName =  java.net.URLEncoder.encode(fileName, "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return downloadFileName;
}

上傳成功後 $("#summernote").summernote('insertImage', data);方法將圖片插入到summernote中,data爲返回的下載路徑。可以看上傳的後臺方法。

如果沒有定義onImageUpload屬性,Summernote會自動把圖片轉換爲Base64格式。

onPaste清除word複製過來的格式。

渲染完成後一個完美的富文本編輯器就出來了。

可以通過以下代碼給編輯器初始值(也可以寫入到初始容器中)

$('#summernote').code("Holle word");

通過以下代碼獲取富文本域中的內容。

var summernote = $('#summernote').summernote('code');

定義一個獲取富文本域中內容的方法。將獲取到的內容在控制檯輸出。可以在此方法中用AJAX請求將數據保存到數據庫中。

function sub() {
    var summernote = $('#summernote').summernote('code');
    console.log(summernote);
}

在富文本編輯器中測試輸入內容。

通過點擊保存按鈕獲取到富文本編輯器中的內容,在控制檯輸出。

注意:由於富文本內容有可能過多,數據庫保存該字段,不能用String類型,長度不夠,MySQL數據庫可以用longtext類型。

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