springboot结合WangEditor富文本编辑器上传图片(包含后台)

环境:
springboot+thymeleaf
application.yml代码如下:

file:
  uploadPath: E:\\images\\
  #  uploadPath: imgupload/
  accessPath: /upload/markPic/

配置文件:

@Configuration
class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String os = System.getProperty("os.name");
        //如果是Windows系统
        if (os.toLowerCase().startsWith("win")) {
            registry.addResourceHandler("/upload/markPic/**")
                    //项目外路径
                    .addResourceLocations("file:E:/images/");

        } else {  //linux 和mac
            registry.addResourceHandler("/img/**")
                    .addResourceLocations("file:/webapps/img");
        }
    }
}

根据WangEditor开发文档,在前端写
这里我有用到textarea,所以

<div id="div1">
    <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
</div>
<textarea id="text1" style="width:100%; height:200px;"></textarea>

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="//unpkg.com/wangeditor/dist/wangEditor.min.js"></script>
<script type="text/javascript">
    const E = window.wangEditor
    const editor = new E('#div1')
    const $text1 = $('#text1')
    editor.config.onchange = function (html) {
        // 第二步,监控变化,同步更新到 textarea
        $text1.val(html)
    }
    editor.create()

    // 第一步,初始化 textarea 的值
    $text1.val(editor.txt.html())
</script>

再加上图片上传,因此完整的代码如下(这里JS我引入的是本地的):

<!-- 引用js -->
<script src="/resources/js/jquery.min.js"></script>
<script type="text/javascript" src="/resources/js/wangEditor.min.js"></script>
<script>
    const E = window.wangEditor
    const editor = new E('#div1')
    const $text1 = $('#text1')

    editor.config.debug = true;
    editor.config.uploadFileName = 'file';
    editor.config.uploadImgMaxLength = 5 // 一次最多上传 5 个图片
    editor.config.uploadImgServer = '/file/uploadEditor';
    editor.config.onchange = function (html) {
        $text1.val(html)
    }

    editor.create();
    // 初始化 textarea 的值
    $text1.val(editor.text.html())
</script>

接下来是后台的代码:根据开发文档,上传成功需要返回的格式为:
成功返回示例:{“errno”: 0,// data 是一个数组,返回图片的线上地址
“data”: [
“图片1地址”,
“图片2地址”,
“……”
]}
因此,我们返回的数据也要对应。

    /**
     * 富文本编辑器上传
     * @param request
     * @param files
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadEditor", method = RequestMethod.POST)
    public JSONObject uploaduploadEditor(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) throws Exception {
        //这里能直接得到文件数组
        List filePathList = new ArrayList<>();
        JSONObject res = new JSONObject();
        if (files == null) {
            throw new IOException("上传失败:文件为空");
        }
        for (MultipartFile file : files) {
            //服务器路径加项目名称
            String imageUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            //图片真实路径
            String fileRealPath = file.getOriginalFilename();
            String suffix = fileRealPath.substring(fileRealPath.lastIndexOf("."));
            String fileName = System.currentTimeMillis()+"_" +suffix;
            //把服务器路径和图片路径拼接起来
            String path = uploadPath;
            File targetFile = new File(path, fileName);
            Object filePath =  accessPath+fileName;
            if(!targetFile.exists()){
                try {
                    targetFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                file.transferTo(targetFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //成功返回示例:{"errno": 0,// data 是一个数组,返回图片的线上地址
            //    "data": [
            //        "图片1地址",
            //        "图片2地址",
            //        "……"
            //    ]}
//            {"errno":0,"data":"/upload/markPic/1610434244822_.jpg"}
            filePathList.add(filePath);
        }
        res.put("errno",0);
        res.put("data",filePathList);
        System.out.println(res);
        return res;
    }

还需要取配置文件的值:

@Value("${file.uploadPath}")
String uploadPath;  //项目地址
@Value("${file.accessPath}")
String accessPath;   //虚拟地址

结果图:
在这里插入图片描述

简单记录一下,晚点会结合七牛云。
不足之处,请多多提出意见,共同进步!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

5210丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值