天天看點

summernote 的快速使用,以及解決圖檔寫入資料庫問題

summernote 是一款優秀的富文本編輯器,外觀優雅,功能強大,使用便捷,支援圖檔自适應展示

官方網站 https://summernote.org/

但是插入圖檔時有個巨大缺陷,summernote預設是将圖檔轉成base64的形式寫入到資料庫中

這樣會給資料庫造成巨大的存儲量,經過多方改造,基本可以滿足開發使用需要,附上代碼

<link href="$!{basePath}/plug-in/summernote/dist/summernote.css" target="_blank" rel="external nofollow" rel="stylesheet"/>

<script src="$!{basePath}/plug-in/summernote/dist/summernote.js"></script>

<script src="$!{basePath}/plug-in/summernote/lang/summernote-zh-CN.js"></script>

<div class="col-sm-12" style="padding: 0;">

    <div id="summernote">$!{anInfo.answer}</div>

</div>

<script type="text/javascript">

$('#summernote').summernote({

    height : '220px',

    lang : 'zh-CN',

       callbacks: {

         onImageUpload: function(files,editor,$editable) {

                 sendFile(this,files[0], editor,$editable);

         }

       }

});

//ajax上傳圖檔

function sendFile(obj,file, editor,$editable) {

    var  filename=false;

    try{

        filename=file['name'];

    }catch(e){

        filename=false;

    }

    if(!filename){

        $(".note-alarm").remove();

    }

    //防止重複送出

    var formData = new FormData();

    formData.append("file", file);

    //formData.append("key",filename);//唯一參數性

    $.ajax({

        url: "$!{basePath}/fileUpload/uploadEditorImg.do",//路徑是你控制器中上傳圖檔的方法

        data: formData,

        cache: false,

        contentType: false,

        processData: false,

        type: 'POST',

        success: function (data) {

            debugger;

            $(obj).summernote('insertImage', data.path);

        }

    });

}

</script>

//上傳背景

@RequestMapping(value = "uploadEditorImg", method = { RequestMethod.POST, RequestMethod.GET })

@ResponseBody

public synchronized Map<String, Object> uploadEditorImg(HttpServletRequest request, HttpServletResponse response) throws Exception {

    MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;

    Map<String, Object> map = new HashMap<>();

    Iterator<String> iterator = mr.getFileNames();

    while (iterator.hasNext()) {

        MultipartFile multipartFile = mr.getFile(iterator.next());

        // 原檔案名

        String oldFileName = multipartFile.getOriginalFilename();

        // 檔案字尾

        String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));

        // 檔案夾

        String folder = sdf.format(new Date());

        // 檔案相對路徑 basePath=/opt

        String frontPath = basePath + File.separator + FileEnum.EDITOR + File.separator + folder;

        File dir = new File(frontPath);

        if (!dir.exists()) {

            dir.mkdirs();

        }

        // 新檔案名稱

        String newFileName = UUIDGenerator.getId() + suffix;

        File newFile = new File(frontPath + File.separator + newFileName);

        multipartFile.transferTo(newFile);

        map.put("oldFileName", oldFileName);

        map.put("newFileName", newFileName);

        map.put("filePath", folder + File.separator + newFileName);

        map.put("fullFilePath", frontPath + File.separator + newFileName);

        //domain.name=www.xxx.cn

        map.put("path", PropertieUtil.readProperty("domain.name") + "/fileUpload/showEditorImg.do?fullpath=" + folder + File.separator + newFileName);

        System.out.println(PropertieUtil.readProperty("domain.name") + "/fileUpload/showEditorImg.do?fullpath=" + folder + File.separator + newFileName);

    }

    return map;

}

//展示

@RequestMapping(value = "showEditorImg", method = { RequestMethod.POST, RequestMethod.GET })

@ResponseBody

public void showEditorImg(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String fullpath = request.getParameter("fullpath"); // 檔案名

    FileInputStream fileInputStream = null;

    OutputStream outStream = null;

    try {

        fileInputStream = new FileInputStream(basePath + File.separator + FileEnum.EDITOR + File.separator + fullpath);

        int i = fileInputStream.available(); // 得到檔案大小

        byte data[] = new byte[i];

        fileInputStream.read(data); // 讀資料

        response.setContentType("image/*"); // 設定傳回的檔案類型

        outStream = response.getOutputStream(); // 得到向用戶端輸出二進制資料的對象

        outStream.write(data); // 輸出資料

    } catch (Exception e) {

        LogUtil.error("系統找不到檔案:" + fullpath);

    } finally {

        if (outStream != null) {

            outStream.flush();

            outStream.close();

        }

        if (fileInputStream != null) {

            fileInputStream.close();

        }

    }

}

注:預設插入圖檔時是以px設定寬度,這樣沒法滿足自适應要求,注意單擊圖檔選擇百分比,PC端和移動端展示都可以滿足自适應