summernote 的快速使用,以及解决图片写入数据库问题

summernote 是一款优秀的富文本编辑器,外观优雅,功能强大,使用便捷,支持图片自适应展示
官方网站 https://summernote.org/

但是插入图片时有个巨大缺陷,summernote默认是将图片转成base64的形式写入到数据库中
这样会给数据库造成巨大的存储量,经过多方改造,基本可以满足开发使用需要,附上代码

<link href="$!{basePath}/plug-in/summernote/dist/summernote.css" 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端和移动端展示都可以满足自适应
 

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 配置数据库连接信息 在application.properties文件中添加以下配置信息: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 2. 添加MyBatis依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> ``` 3. 创建数据表 创建一个名为user的数据表,包含id、name和age三个字段。 4. 创建实体类 创建一个User实体类,包含id、name和age三个属性,同时添加对应的getters和setters方法。 5. 创建Mapper层 创建一个UserMapper接口,定义一个insert方法,用于向数据库插入User对象。 ``` @Mapper public interface UserMapper { @Insert("INSERT INTO user(name, age) VALUES (#{name}, #{age})") int insert(User user); } ``` 6. 创建Service层 创建一个UserService接口,定义一个addUser方法,用于向数据库插入User对象。 ``` @Service public interface UserService { int addUser(User user); } ``` 在UserService接口的实现类UserServiceImpl中注入UserMapper,并实现addUser方法。 ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public int addUser(User user) { return userMapper.insert(user); } } ``` 7. 创建Controller层 创建一个UserController类,注入UserService,并添加addUser方法,用于接收前端传递的User对象,并调用UserService的addUser方法插入数据库中。 ``` @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @PostMapping("/add") public int addUser(@RequestBody User user) { return userService.addUser(user); } } ``` 至此,使用SpringBoot MyBatis向数据库写入数据的整个流程完成。可以通过Postman等工具测试接口,向数据库插入数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值