wangEditor富文本编辑器

 富文本编辑器,Rich Text Editor, 简称 RTE, 是一种可内嵌于浏览器,所见即所得的文本编辑器. 
CSDN的markdown编辑器便是一种富文本编辑器.

  蓝莓商城商品详情这一部分的编辑需要使用富文本编辑器.本来想使用百度的ueditor的,但是弄了好久依然还是有问题.所以就放弃了.ueditor配置确实比较复杂,官方的文档也没有很好的说清楚,错误提示不够明了,出错时未提示具体的原因.

  最后找到这个wangEditor.相比ueditor,配置更加简单,使用更加方便.其功能虽不及ueditor多,但是应付一般的需求足够了. 
 

流程说明

 由于对于图片上传整个流程比较复杂,所以本文仅对其进行说明. 
 图片上传的流程是,当页面选择图片后,将会创建XMLHttpRequest请求,将图片数据发送给服务端,服务端接收后将图片保存到本地,再将图片路径返回给客户端,客户端接收到图片路径后,创建元素,并将图片路径赋给src,最后再把该元素插入到编辑器中. 
 
 // 定义 xhr 发送请求给服务端
  var xhr = new XMLHttpRequest();
   xhr.open('POST', uploadImgServer);

客户端配置说明
下载
直接下载:https://github.com/wangfupeng1988/wangEditor/releases 
使用npm下载:npm install wangeditor (注意 wangeditor 全部是小写字母) 
使用bower下载:bower install wangEditor (前提保证电脑已安装了bower) 
使用CDN://unpkg.com/wangeditor/release/wangEditor.min.js

调试阶段推荐使用方式1中的未压缩版本,因为如果出现问题也好调试和查找. 
下载后将目录里的wangEditor.js放入工程目录中.只需要这个文件,其他的不需要. 
 
我放在webapp下的wangEditor路径下. 


前端配置
引入js文件 
contextPathOfStatic这里是我的项目路径下的static文件夹:http://localhost:8080/lanmei-os/static

<script type="text/javascript" src="${contextPathOfStatic}/wangEditor/wangEditor.js"></script>
1
jsp页面添加

<div id="editor">
 <!-- 默认显示 -->
   <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
</div>

这里我创建3个按钮进行测试

<button id="editorSetBtn">设置内容</button>
<button id="editorGetBtn1">获取内容1</button>
<button id="editorGetBtn2">获取内容2</button>
js文件编写
$(function(){

    var E = window.wangEditor;
    //这里的id为<div id="editor"中的id.
    var editor = new E('#editor');
    // 配置服务器端地址,也就是controller的请求路径,不带项目路径,前面没有/
    editor.customConfig.uploadImgServer = 'commodity/upload/editor/img';
    //配置属性名称,绑定请求的图片数据
    //controller会用到,可以随便设置,但是一定要与controller一致
    editor.customConfig.uploadFileName = 'img';
    //创建编辑器
    editor.create();

    $("#editorSetBtn").click(function(){
        //这是设置编辑器内容
        editor.txt.html("dsafdfadsfdafdsfds");
    })
     $("#editorGetBtn1").click(function(){
      //获取编辑器的内容,带样式
      //一般使用这个获取数据,通过ajax发送给服务端 ,然后服务端以String接收,保存到数据库.
         alert(editor.txt.html());
    })
     $("#editorGetBtn2").click(function(){
        //获取编辑器的内容,不带样式,纯文本
         alert(editor.txt.text());
    })
})

程序加载完之后页面就会出现编辑器. 


客户端设置完成

服务端配置
WEB层创建Controller
@Controller
@RequestMapping(path="/commodity")
public class CommodityController {
    @Autowired
    AddCommodityService   addCommodityService;
    @Autowired
private static final Logger logger = LoggerFactory.getLogger("CommodityController.class");
    @ResponseBody
    @RequestMapping(path="/upload/editor/img")
    //RequestParam中的属性名称要和前端定义的一致,上面说明了.所以写"img"
    //使用List<MultipartFile>进行接收
    //返回的是一个Dto类,后面会说明,使用@ResponseBody会将其转换为Json格式数据
    public ImgResultDto uploadEditorImg(@RequestParam("img") List<MultipartFile> list) {    
        //这里是我在web中定义的两个初始化属性,保存目录的绝对路径和相对路径,你们可以自定义    
        String imgUploadAbsolutePath = request.getServletContext().getInitParameter("imgUploadAbsolutePath");
        String imgUploadRelativePath = request.getServletContext().getInitParameter("imgUploadRelativePath");

      //服务曾处理数据,返回Dto
        ImgResultDto imgResult
                = addCommodityService.upLoadEditorImg(list, imgUploadAbsolutePath, 
                                                imgUploadRelativePath,1);
            return imgResult;           
    }

}

服务层创建Service类
服务层创建Service接口类

public interface AddCommodityService {
    /**
     * 上传商品图片
     * @param files
     */
    ImgResultDto upLoadEditorImg(List<MultipartFile> list,
            String UploadAbsolutePath,
            String UploadRelativePath,
            int commodityId);
}

服务层创建Service接口实现类
这里需要注意的是保存地址,我是保存在项目路径下,有的会保存在文件系统根目录下,比如windows可能是D://xxx/xx,linux是/xx/xx,那么返回给客户端的地址就会不一样.需要根据实际情况设置

public class AddCommodityServiceImpl extends BaseService  implements AddCommodityService{
    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    CommodityImageMapper commodityImageMapper;
    @Autowired
    private DruidDataSource dataSource; 
    @Autowired
    private SqlSessionFactoryBean sqlSessionFactory;
/**
     * 图片上传处理
     */
    @Override
    public ImgResultDto upLoadEditorImg(List<MultipartFile> list,
            String UploadAbsolutePath,
            String UploadRelativePath,
            int commodityId) {

        //获取当前登录的管理员
        //CmsAdmin admin = (CmsAdmin) SessionUtils.getSession("currenLogintAdmin");
        CmsAdmin admin = new CmsAdmin("测试用户");
        //工程绝对路径
        String imgUploadAbsolutePath = UploadAbsolutePath;
        //工程相对路径
        String imgUploadRelativePath = UploadRelativePath;
        logger.debug("files.length = " + list.size() );
        ImgResultDto imgResultDto = new ImgResultDto();
        //这里定
        String[] urlData = new String[5];
        int index = 0;
        try {
            for(MultipartFile img : list) {
              //获取原始文件名,比如你上传的是 图片.jpg,则fileName=图片.jpg
                String fileName = img.getOriginalFilename();
                if(fileName == "") {
                    continue;
                }
                logger.debug("file  name = " + fileName);
                String finalPath = imgUploadAbsolutePath + imgUploadRelativePath;  //绝对路径 + 相对路径
                //为了保证文件名不一致,因此文件名称使用当前的时间戳和4位的随机数,还有原始文件名组成
                //觉得实际的企业开发不应当使用原始文件名,否则上传者使用一些不好的名字,对于下载者就不好了.
                //这里为了调试方便,可以加上.
                String finalFileName =  (new Date().getTime()) + Math.round(Math.random() * 1000)  //文件名动态部分
                                    + fileName; //文件名 原始文件名        
                File newfile = new File( finalPath + finalFileName);
                logger.debug("创建文件夹 = " + newfile.mkdirs() +  "  path = " + newfile.getPath());
                logger.debug("" + newfile.getAbsolutePath());
                //保存文件到本地
                img.transferTo(newfile);
                logger.debug("上传图片成功");
                //持久化到数据库
                CommodityImage commodityImage = new  CommodityImage(commodityId, imgUploadRelativePath,
                        finalFileName,(byte)(0),admin.getLoginJobnum(), new Date());

                commodityImageMapper.insert(commodityImage);
                logger.debug("数据库写入图片成功");  
                //这里的路径是项目路径+文件路径+文件名称
                //这么写不是规范的做法,项目路径应是放在前端处理,只需要发送相对路径和文件名称即可,项目路径由前端加上.
                urlData[index++] = "http://localhost:8080/lanmei-cms/"+imgUploadRelativePath + finalFileName;
                logger.debug("index = " + index 
                        + "  url = " + urlData[0]);
                //设置异常代号
                imgResultDto.setErrno(0);
            }
            imgResultDto.setData(urlData);
            //返回Dto
            return imgResultDto;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return imgResultDto;
        }

    }

}

Dto编写
Dto 只是一个普通的pojo类,没有业务方法,只有属性和构造器,getter and setter.主要用于层间传输数据,更详细的说明自行百度.

public class ImgResultDto<T> {

    private int  errno;//错误代码

    private String[] data;//存放数据
    //构造器
    //getter and setter

前端接收处理
添加 customInsert: function (insertImg, result, editor)这段程序 
result是返回的json数据 
因为上面只是上传了一张图片,保存在数组索引0里 
因此通过下面获取图片地址. 
var url = result.data[0];

    // 上传图片 hook 
    uploadImgHooks: {

        before: function before(xhr, editor, files) {
            // 图片上传之前触发

            // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
            // return {
            //     prevent: true,
            //     msg: '放弃上传'
            // }
        },
        success: function success(xhr, editor, result) {
            // 图片上传并返回结果,图片插入成功之后触发
            console.log("插入图片成功 success result = " + result.errno + "  path = " + result.data[0] );
        },
        fail: function fail(xhr, editor, result) {
            console.log(" fail result = " + result.errno + "  path = " + result.data[0] );
            // 图片上传并返回结果,但图片插入错误时触发
        },
        error: function error(xhr, editor) {
            // 图片上传出错时触发
            console.log("error result = " + result.errno + "  path = " + result.data[0] );
        },
        timeout: function timeout(xhr, editor) {
            // 图片上传超时时触发
            console.log("timeout result = " + result.errno + "  path = " + result.data );
        },

       // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式,可使用该配置 
        //--------------添加这段程序------------------
        customInsert: function (insertImg, result, editor) {
            // 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
            // insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果

            // 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:

            //-----------修改这里------------------
            //获取返回的图片地址
            var url = result.data[0];

            insertImg(url);

            console.log("插入图片 url = " + url );
            // result 必须是一个 JSON 格式字符串!!!否则报错
        }
    },

    // 是否上传七牛云,默认为 false
    qiniu: false

};

总结
  本文说明了如何在Java WEB项目中使用富文本编辑器wangEditor,包括前端配置和后端处理.仅说明其简单的用法,业务也未考虑的很周详.更多功能扩展请看官方的说明. 
  项目的完整程序请看蓝莓商城项目,后面我会陆续完善.
参考:https://blog.csdn.net/u011676300/article/details/80345152

猜你喜欢

转载自blog.csdn.net/qq_34107571/article/details/85262842