wangEditor+SringBoot富文本编辑器使用(图片上传)

最近项目中使用到了wangEditor插件,在此记录使用过程。

wangEditor+SringBoot富文本编辑器使用(图片上传)_第1张图片

官网下载wangEditor:https://github.com/wangfupeng1988/wangEditor/releases

思路:点击插件中上传图片,图片上传至服务器临时图片文件夹下,当最后点击确认保存按钮时,再把临时文件夹下的图片复制到正式的文件夹下面。

在HTML中引入wangEditor.js:


HTML中只需要顶一个富文本编辑器容器

js初始化wangEditor:


editorPic接口给后台传图片文件,后台返回图片存入临时文件的路径:

    /**
     * 富文本图片存入临时文件夹
     *
     * @param file
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/editorPic", method = RequestMethod.POST, headers = "Accept=application/json")
    @ResponseBody
    public HttpResponseEntity updateLabel(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest req) throws Exception {
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        String parent = remoteProperties.getBaseUrl() + "temp/";
        MultipartFile[] multipartFiles = new MultipartFile[1];
        multipartFiles[0] = file;
        FileOperate fileOperate = new FileOperate();
        List editorPic = fileOperate.imageUpload(multipartFiles, parent);

        if (!editorPic.isEmpty()) {
            httpResponseEntity.setCode(Constans.SUCCESS_CODE);
            httpResponseEntity.setData(remoteProperties.getHttpUrl() + "temp/" + editorPic.get(0));
        } else {
            logger.error("editorPic  富文本编辑器临时图片的存储 >>>>>>>>>>>   异常");
            httpResponseEntity.setCode(Constans.EXIST_CODE);
            httpResponseEntity.setMessage(Constans.EXIST_MESSAGE);
        }
        return httpResponseEntity;
    }
HttpResponseEntity.java:
package com.aim.questionbanksystem.beans;

import lombok.Data;

import java.io.Serializable;

@Data
public class HttpResponseEntity implements Serializable {

    private String code; //状态码
    private Object data; //内容
    private String message; //状态消息

}
RemoteProperties.java:
package com.aim.questionbanksystem.config.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Configuration
@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false)
@PropertySource(value = {"classpath:config/remote.properties"},encoding="utf-8")
@Data
@Component
public class RemoteProperties {

    private String uploadFilesUrl;
    private String uploadPicUrl;
    private String httpUrl;
    private String baseUrl;
    private String webUrl;

    private String msgTemplateModuleCodeReg;
    private String msgTemplateModuleCodeFindPsw;
    private String msgSignName;

    private String codeLegalTime;
}
remote.properties:
#本地地址
remote.httpUrl=http://localhost:8085/imgFiles/
remote.baseUrl=D:/TDDOWNLOAD/tomcat8.0.38-1-normal/apache-tomcat-8.0.38/webapps/imgFiles/

以上步骤为,点击富文本上传图片,将图片上传至服务器临时图片文件夹。

当点击确认保存内容(保存富文本编辑器内容,将内容存至数据库)的时候:

js:

    function insert(){
        var editorContent = editor1.txt.html();
        var data = {
            "editorContent": editorContent,
        }
        commonAjaxPost(true, '/insert', data, function(result){
            console.log(result);
        });
    }

service层:

    public int addQuestionInfo(Map map) {

        TestEntity testEntity = new TestEntity ();

        testEntity .setEditorContent(map.get("editorContent").toString());

        //题干内容配图存入数据库的父路径
        String picImport = "final/";
        FileOperate fileOperate = new FileOperate();
        File dir = new File(remoteProperties.getBaseUrl() + picImport);
        //新闻配图存储路径
        String picParent = remoteProperties.getBaseUrl() + picImport;
        //拆分内容中的图片
        String regex = "/final/"; //正式文件夹
        String replacement = "/temp/";  //临时文件夹
        List pics = matchPic(testEntity.getEditorContent(), regex, replacement);
        //题干内容中有图片
        if (!pics.isEmpty()) {
            String imgUrl = "";
            //题干内容图片存入数据库的附路径
            String newsContentPicImport = "final/";
            //题干图片原路径
            String oldContentPicImport = "temp/";
            //题干内容图片存储路径
            String newsContentPictureParent = remoteProperties.getBaseUrl() + newsContentPicImport;
            for (int f = 0; f < pics.size(); f++) {
                if (f == 0) {
                    imgUrl += pics.get(f);
                } else {
                    imgUrl += "," + pics.get(f);
                }
                int i = 0;
                try {
                    i = fileOperate.copyFile(oldContentPicImport + pics.get(f), newsContentPictureParent + pics.get(f), remoteProperties.getBaseUrl());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (i == 0) {
                    fileOperate.deleteDir(dir);
                    return 0;
                } else if (i == -1) {
                    fileOperate.deleteDir(dir);
                    return -1;
                } else if (i == -2) {
                    fileOperate.deleteDir(dir);
                    return -2;
                }
            }
            testEntity.setEsitorContent(testEntity.getEditorContent().replaceAll(replacement, regex));
        }

        int i = testEntityMapper.addQuestionInfo(testEntity);
        if (i != 0) {
            //fileOperate.deleteDir(dir);
            return 1;
        } else {
            //fileOperate.deleteDir(dir);
            return -3;
        }


    }

    public List matchPic(String content, String regex, String replacement) {
        List pics = new ArrayList();
        Document document = Jsoup.parse(content.replaceAll(regex, replacement));
        Elements ele = document.getElementsByTag("img");
        for (int i = 0; i < ele.size(); i++) {
            String imgU = ele.get(i).attr("src");
            pics.add(i, imgU.substring(imgU.indexOf("temp/") + 5, imgU.length()));
        }
        return pics;
    }

存到数据库的字段内容:

你可能感兴趣的:(前端)