summernote编辑器 图片上传
原创    cannot    发表于:2018-04-28 14:24:11
  阅读 :218   收藏   编辑

summernote默认上传的图片是以二进制的形式存入数据库字段中,
占用太多的资源,这里修改为保存图片地址,

官网:https://summernote.org/ 相关资源的引入,在此下载

本文在spring mvc 环境下测试通过,具体环境参考见鬼网文章:教你一步步搭建ssm框架,第一步实现springmvc下的页面跳转 - 2018

该环境pom.xml没有引入jstl依赖
<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
</dependency>

html.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<c:set var="basepath" value="${pageContext.request.contextPath}/" />
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.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>

<!-- include summernote css/js -->
<link href="${basepath}statics/htmlEdit/css/summernote.css" rel="stylesheet">
<script src="${basepath}statics/htmlEdit/summernote.js?v=1"></script>
<script src="${basepath}statics/htmlEdit/lang/summernote-zh-CN.js"></script>
</head>
<body>
    <div id="summernote"></div>
    <button id="btn">btn</button>
    <hr>
    <div id="html"></div>
</body>
<script>
$(document).ready(function() {
      var $placeholder = $("#summernote");
      $('#summernote').summernote({
            lang: 'zh-CN',
            placeholder: '开始写作...',
          tabsize: 2,
          height: 300,
          toolbar: [
              ['style', ['style']],
              ['font', ['bold', 'underline', 'clear']],
              ['fontname', ['fontname']],
              ['color', ['color']],
              ['para', ['ul', 'ol', 'paragraph']],
              ['table', ['table']],
              ['insert', ['link', 'picture']],
              ['view', ['fullscreen', 'codeview']]
         ],
        callbacks: {
          onInit: function() {
              //init
          },
          onFocus: function() {
              //focus
          },
          onImageUpload: function(files, editor, $editable) {
              data = new FormData();  
              data.append("file", files[0]);  
            $.ajax({  
                data : data,  
                type : "POST",  
                url : "${basepath}execUpload",   
                cache : false,  
                contentType : false,  
                processData : false,  
                dataType : "json",  
                success: function(data) {  
                    $('#summernote').summernote('insertImage', '${basepath}statics/'+data.path);  
                },  
                error:function(){  
                    alert("上传失败");  
                }  
            });  
          }
        }
    });
});

$("#btn").click(function(){
    var markupStr = $('#summernote').summernote('code');
    $("#html").html(markupStr)
})
</script>
</html>

UploadController.java

package com.faceghost.app.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

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

@Controller
public class UploadController {


    /**
     * 文件上传
     * @param request
     * @return
     */
    @RequestMapping("/execUpload")
    @ResponseBody
    public BaseVo execUpload(MultipartFile file , String fileName, HttpServletRequest request) throws Exception {
        BaseVo vo = new BaseVo();
        //开始
        System.err.println("upload s ...");

        System.err.println("fileName:" + fileName);

        String oFileName = file.getOriginalFilename();

        System.err.println("oFileName:" + oFileName);

        /**
         * 获取文件类型
         * 
         */
        String fileType = oFileName.substring(oFileName.lastIndexOf("."),oFileName.length());

        /**
         * 获取项目webapp目录下的upload的路径
         */
        String prePath  = request.getSession().getServletContext().getRealPath("statics");

        System.err.println("prePath:" + prePath);

        /**
         * 上传保存后新的文件名称
         */
        String newFileName = UUID.randomUUID().toString() + fileType;

        System.err.println("newFileName:" + newFileName);



        /**
         * 复制流,或者,IOUtils.copy(input, output);
         */
        InputStream inputStream = file.getInputStream();
        File newFile = new File(prePath + File.separator + newFileName);

        OutputStream outputStream = new FileOutputStream(newFile);
        byte[] b = new byte[inputStream.available()] ;
        inputStream.read(b);
        outputStream.write(b);

        inputStream.close();
        outputStream.close();

        System.err.println("upload e ...");
        vo.setPath(newFileName);
        return vo;
    }

}


class BaseVo implements Serializable {
    private String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

}

效果

评论
条评论