富文本使用之wangEditor3

一、介绍:

wangEditor —— 轻量级 web 富文本编辑器,配置方便,使用简单。支持 IE10+ 浏览器。

二、使用方式:

三、使用:

重点是图片的上传和富文本内容的获取。

1.图片上传:

①存放在一个临时的文件夹里。

②将图片地址返给前台,富文本显示图片。

2.内容获取:

①获取富文本的内容,截取内容里的图片标签。

②将图片存入到一个新的文件夹里,替换图片的地址。

③将新的富文本的内容存储到数据库里。(这里我未作处理)

前台代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>富文本的使用</title>
    <style type="text/css">
        body {
            width: 800px;
            margin: 0 auto 0 auto;
        }
    </style>
</head>
<body>

<!--wangEditor 使用 B-->
<div id="div1">
</div>
<!--wangEditor 使用 E-->
<button id="addBtn" onclick="addNews()">增加</button>

</body>
<script type="text/javascript" src="../release/wangEditor.js"></script>
<script src="js/jquery-3.2.1.js"></script>
<script type="text/javascript">
    var httpurl = "http://localhost:8081";

    //富文本使用
    var E = window.wangEditor;
    var editor = new E(‘#div1‘);
    //重新设置富文本的内容
    editor.customConfig.menus = [
        ‘head‘,  // 标题
        ‘bold‘,  // 粗体
        ‘fontSize‘,  // 字号
        ‘italic‘,  // 斜体
        ‘underline‘,  // 下划线
        ‘foreColor‘,  // 文字颜色
        ‘link‘,  // 插入链接
        ‘justify‘,  // 对齐方式
        ‘image‘,  // 插入图片
        ‘undo‘,  // 撤销
        ‘redo‘  // 重复
    ];
    // 隐藏“网络图片”tab
    editor.customConfig.showLinkImg = false;
    // 将图片大小限制为 3M
    editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
    // 限制一次最多上传 1 张图片
    editor.customConfig.uploadImgMaxLength = 1;
    //开启wangEditor的错误提示
    editor.customConfig.debug=true;
    // 关闭粘贴样式的过滤
    editor.customConfig.pasteFilterStyle = false;
    // 忽略粘贴内容中的图片
    editor.customConfig.pasteIgnoreImg = true;

    //上传图片 将图片以文件的形式传给后台进行操作返回图片 url
    editor.customConfig.customUploadImg = function (files, insert) {
        var date = new FormData();
        date.append("file", files[0]);
        $.ajax({
            type: "POST",
            url: httpurl + "/test/upload",
            data: date,
            dataType: ‘json‘,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (result) {
                insert(result.data);// insert 是获取图片 url 后,插入到编辑器的方法
            }
        })
    };
    editor.create();//创建富文本

    /**
     * 添加企业新闻
     */
    function addNews() {
        var formData = new FormData();
        formData.append("news",editor.txt.html());
        $.ajax({
            type: "POST",
            url: httpurl + "/test/addNews",
            data: formData,
            dataType: ‘json‘,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (result) {
                console.log(result);
            }
        })
    }
</script>
</html>

后台代码:

/**
 * 图片上传
 * @param request
 * @param file
 * @return
 */
public JSONObject upload(HttpServletRequest request,MultipartFile file) {
    JSONObject imgPathObject = new JSONObject();
    Map map = new HashMap();
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    List<FileItem> list = null  ;
    if(isMultipart){
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");

        try {

            //获取文件名(带后缀名)
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //企业新闻id
            String entNewsImgId = UUIDUtil.getOneUUID();
            fileName = entNewsImgId + suffixName;

            //获取文件输入流
            InputStream input = file.getInputStream();

            // 获取当前时间
            String format = DateUtil.DEF_DATE_FORMAT_STR;
            String strDate = DateUtil.dateToString(new Date(),format);
            String StrDateTime = strDate.substring(0, 10);

            //获取工程路径
            String serverAddress = request.getServletContext().getRealPath("/");
            String entNewsImgPath = serverAddress +"tempRes/busiPic/" + StrDateTime +"/" + fileName;
            int result = writeToLocal(entNewsImgPath, input);
            String imgPath = "http://localhost:8081/tempRes/busiPic/" + StrDateTime +"/" + fileName;
            if(result == 1) {
                map.put("data", imgPath);
                String  entNewsStr = JSONObject.toJSONString(map);
                imgPathObject = JSONObject.parseObject(entNewsStr);

            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    return imgPathObject;
}

/**
 * 将InputStream写入本地文件
 * @param filePath 写入本地目录
 * @param input 输入流
 * @throws IOException
 */
private static int writeToLocal(String filePath, InputStream input)  {
    //定义每次读取的长度
    int index = -1;
    //定义每次读取字节的大小与保存字节的数据
    byte[] bytes = new byte[1024];
    FileOutputStream downloadFile;
    try {
        //保证创建一个新文件
        File file = new File(filePath);
        if (!file.getParentFile().exists()) { // 如果父目录不存在,创建父目录
            file.getParentFile().mkdirs();
        }
        file.createNewFile();

        downloadFile = new FileOutputStream(filePath);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return 0;
    } catch (IOException e) {
        e.printStackTrace();
        return 0;
    }
    return 1;
}

/**
 * 获取富文本内容
 * @param request
 * @param file
 * @return
 */
public JSONObject addNews(HttpServletRequest request, MultipartFile file) {
    Map map = new HashMap();
    //新闻的UUID
    String entNewsId = UUIDUtil.getOneUUID();
    String newsCon = "";//新的新闻内容
    String newsImgPath = "";//新闻图片路径
    String newsContent = request.getParameter("news");//获取新闻内容
    System.out.println(newsContent);
    //截取图片路径
    String tempSrc= "<img src=\"";
    String[] imgStr = newsContent.split(tempSrc);
    String[] imgPathStr = new String[imgStr.length];//图片路径数组
    System.out.println(imgStr.length);
    if(imgStr.length > 1) {
        String[] imgLengthStr = imgStr[1].split("\"");
        int imgLength = imgLengthStr[0].length();

        for (int i=1; i< imgStr.length; i++) {
            newsImgPath = imgStr[i].substring(0,imgLength);
            System.out.println(newsImgPath);
            //改变图片路径
            String tempPort = "8081/";
            String tempImgPath = request.getServletContext().getRealPath("/") + newsImgPath.split(tempPort)[1];
            String tempImgUUID = newsImgPath.substring(newsImgPath.lastIndexOf("/")+1);
            System.out.println(tempImgPath);
            String imgPathNewAbove = request.getServletContext().getRealPath("/");
            String imgPathNewBehind ="busiPic/entNewsPic/"+ entNewsId +"/pic_" + tempImgUUID;
            String imgPathNew = imgPathNewAbove + imgPathNewBehind;
            File oldFile = new File(tempImgPath);
            File newFile = new File(imgPathNew);
            Boolean bln = copyFile(oldFile,newFile);
            if(bln)
                imgPathStr[i-1] = newsImgPath.split(tempPort)[0] + tempPort + imgPathNewBehind;
        }

        newsCon = imgStr[0];
        for (int i=1; i< imgStr.length; i++) {
            newsCon += tempSrc + imgPathStr[i-1] + imgStr[i].substring(imgLength);
        }
        System.out.print(newsCon);
        map.put("newsContent",newsCon);

    }else {
        map.put("newsContent",newsContent);
    }
    String  newContentStr = JSONObject.toJSONString(map);
    JSONObject result = JSONObject.parseObject(newContentStr);
    return result;
}

/**
 * 复制文件
 * @param source
 * @param dest
 * @throws IOException
 */
public static boolean copyFile(File source, File dest){

    //保证创建一个新文件
    if (!dest.getParentFile().exists()) { // 如果父目录不存在,创建父目录
        dest.getParentFile().mkdirs();
    }
    if (dest.exists()) { // 如果已存在,删除旧文件
        dest.delete();
    }
    InputStream input = null;
    OutputStream output = null;
    try {
        dest.createNewFile();//创建文件
        input = new FileInputStream(source);
        output = new FileOutputStream(dest);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buf))>-1) {
            output.write(buf, 0, bytesRead);
        }
        output.close();
        input.close();
    }catch (IOException e) {
        e.printStackTrace();
    }catch(Exception e){
        e.printStackTrace();
        return false;
    }
    return true;
}

样式如图:

原文地址:https://www.cnblogs.com/nananana/p/9025605.html

时间: 2024-08-02 12:55:54

富文本使用之wangEditor3的相关文章

富文本编辑器选择使用

之前使用过百度editer ,还有kindeditor..... 这些富文本编辑器都有一个共同点,相对还是打,有些功能是我不需要的,然后文档还又臭又长!!重点还有就是图片上传那个功能,非要还要什么检测下, 导致我现在一点不想用! 这是我看过最简单的,文档最详细的富文本编辑器了! 当然开源! 文档地址: https://www.kancloud.cn/wangfupeng/wangeditor3/335775 是个人都会用!

微信小程序富文本-wxParse的使用

最近小程序蛮火的,公司要做于是学了一点点小程序 不知道你们有没有遇到过这种问题: 从公司服务器获取的文章内容是有HTML标签格式的一段内容,但是微信是不支持这些标签的,怎么办呢? 1.一般网站后台的文章是这样的,带有很多的html标签(这里是截取的今日头条某文章内容),但是小程序并不支持,它会以文本直接显示 怎么办呢? 2.在这个时候可以考虑 wxParse wxParse信息 版本号0.1 历史版本号0.2 具体代码请查看仓库分支V1 github地址: https://github.com/

TinyMCE(富文本编辑器)

[转]TinyMCE(富文本编辑器)在Asp.Net中的使用方法 官网演示以及示例代码:https://www.tinymce.com/docs/demo/image-tools/ 转自:http://www.cnblogs.com/hahacjh/archive/2010/07/24/1784268.html TinyMCE 在Asp.Net中的使用方法其实挺简单的,从官方网站下载TinyMCE),然后将里面的jscripts目录拷到你的网站目录 假设你的aspx页面中某一个地方需要用到编辑器

Java 实现HTML富文本导出至word完美解决方案

一. 问题的提出 最近用java开发一个科技项目信息管理系统,里面有一个根据项目申请书的模板填写项目申报信息的功能,有一个科技项目申请书word导出功能. 已有的实现方式:采用标准的jsp模板输出实现,简单地说,就是把数据渲染进jsp页面,然后将此页面另存为doc文档,从而达到word导出效果.但是存在以下几个问题: (1) 由于导出的html网页格式,打开word后,默认显示的视图模式为WEB版式视图: (2) 修改word文档后,会新增一个相关联的文件夹,word的html中会引用这个文件夹

Android富文本编辑器RichEditor的使用

以前有个项目做一个笔记本类似的东西,觉得写的不太好,最近重新写,就发现了这个富文本编辑器他的效果是这样的 感觉有点厉害啊 废话不多说开始撸码 1先添加依赖 dependencies { compile 'jp.wasabeef:richeditor-android:1.2.0' } 2写布局 <jp.wasabeef.richeditor.RichEditor android:id="@+id/editor" android:layout_width="match_pa

C# 富文本的使用

一般使用的是百度富文本编辑器: http://ueditor.baidu.com/website/download.html           下载地址 使用方法: 前台 后台:

商城项目整理(四)JDBC+富文本编辑器实现商品增加,样式设置,和修改

UEditor富文本编辑器:http://ueditor.baidu.com/website/ 相应页面展示: 商品添加: 商品修改: 前台商品展示: 商品表建表语句: 1 create table TEST.GOODS_TABLE 2 ( 3 gid NUMBER not null, 4 gname VARCHAR2(90), 5 gdetails CLOB, 6 gpicture VARCHAR2(100), 7 gprice NUMBER, 8 gleixing NUMBER, 9 gpi

关于富文本编辑器UEditor

2017.1.18,星期三?     关于富文本编辑器:     富文本编辑器,Rich Text Editor, 简称 RTE, 是一种可内嵌于浏览器,所见即所得的文本编辑器. 富文本编辑器不同于文本编辑器,程序员可到网上下载免费的富文本编辑器内嵌于自己的网站或程序里(当然付费的功能会更强大些),方便用户编辑文章或信息.比较好的文本编辑器有kindeditor,fckeditor等. 关于UEditor:官网                           UEditor文档,我们的说明书

ios中label富文本的设置

1.修改不同文字和颜色 // 创建一个富文本 NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:@"哈哈哈哈哈123456789"]; // 修改富文本中的不同文字的样式 [attri addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 5