富文本框TinyMCE4.8上传本地图片基本配置(前端篇)

最近使用了一下TinyMCE富文本框,感觉是非常不错的一款,配置简单,界面优美,完全免费...推荐大家使用。

官方文档也比较容易阅读,大家有兴趣的可以自己去看看https://www.tiny.cloud/docs/quick-start/

这里简单记录一下我自己使用TinyMCE的配置,如果阅读过官方文档的前端配置也是极其简单的。

注意:上传本地图片是TinyMCE 4.3才新引入的功能,所以该配置只适合4.3及其以上,我本次使用的是4.8.2版本的。

<!doctype html>
<html>
<head>
<script src='https://cloud.tinymce.com/stable/tinymce.min.js?apiKey=自己申请的KEY'></script>
<script>
  tinymce.init({
    selector: 'textarea#mytextarea',//意思是将TinyMCE插件放入‘textarea’ID为mytextarea的标签里
    plugins: [ //配置插件:可自己随意选择,但如果是上传本地图片image和imagetools是必要的
      'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
      'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
      'save table contextmenu directionality emoticons template paste imagetools textcolor'
    ],
//工具框,也可自己随意配置
    toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullpage | forecolor backcolor emoticons',   	
    image_advtab: true,
    table_default_styles: {
        width: '100%',
         borderCollapse: 'collapse'
    },
    image_title: false, // 是否开启图片标题设置的选择,这里设置否
    automatic_uploads: true,
 // 图片异步上传处理函数
    images_upload_handler: (blobInfo, success, failure) => { 
        var xhr, formData;

        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', 'FileAction_updateFile');//第一个参数是请求方式,第二个参数是请求地址,我这里配置的是struts的action,如果是其他(PHP等)的可这样配置:xxx.php

        xhr.onload = function () {
            var json;
            if (xhr.status !== 200) {
                failure('HTTP Error: ' + xhr.status);
                return;
            }
            json = JSON.parse(xhr.responseText);            
            if (!json || typeof json.location !== 'string') {
            failure('Invalid JSON: ' + xhr.responseText);
                return;
            }
            success(json.location);
        };

        formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());
        xhr.send(formData);
    }
  });
  </script>
</head>
<body>
<center>
<br>
  <form method="post" action="${pageContext.request.contextPath}/TextareaAction">
    <textarea id="mytextarea" name="test"></textarea>
    <input type="submit" value="提交">
  </form>
</center>
</body>
</html>

这里需要注意的是: 在异步处理函数中xhr.open('POST', 'FileAction_updateFile');第二个参数是后台页面,文件上传的页面,如果文件上传成功,需要返回一个Json数据,其中必须包含一个location数据,比如:

{ location : '/uploaded/image/path/image.png' }

 location记录的是你图片保存的地址,然后返回到前台进行显示。

若不进行返回,异步处理函数将不会执行success(json.location);


后台篇,请稍后...

猜你喜欢

转载自blog.csdn.net/weixin_41660508/article/details/82220667
今日推荐