集成TinyMCE富文本编辑器

若依的基础上集成TinyMCE富文本编辑器

前端bootstrap

TinyMCE官网链接
TinyMCE所需静态资源下载链接

开源项目-若依链接

将TinyMCE静态资源包放入项目中;
代码引入css:

<!-- 引入TinyMCE CSS -->
    <link th:href="@{/ajax/libs/tinymce/js/tinymce/skins/ui/oxide/skin.min.css}" rel="stylesheet"/>

代码引入js:

    <!-- 引入TinyMCE JavaScript -->
    <script th:src="@{/ajax/libs/tinymce/js/tinymce/tinymce.min.js}"></script>
    <script th:src="@{/ajax/libs/tinymce/langs/zh-Hans.js}"></script>

html代码

 <div class="form-group">
                <label class="col-sm-3 control-label">详细内容:</label>
                <div class="col-sm-8">
                    <textarea class="form-control" id="mytextarea"  rows="10" cols="50"></textarea>
                </div>
            </div>

js部分

//上传图片方法
 const example_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', ctx + 'common/upload');

            xhr.upload.onprogress = (e) => {
                progress(e.loaded / e.total * 100);
            };

            xhr.onload = () => {
                if (xhr.status === 403) {
                    reject({ message: 'HTTP Error: ' + xhr.status, remove: true });
                    return;
                }

                if (xhr.status < 200 || xhr.status >= 300) {
                    reject('HTTP Error: ' + xhr.status);
                    return;
                }

                const json = JSON.parse(xhr.responseText);

                if (!json || typeof json.url != 'string') {
                    reject('Invalid JSON: ' + xhr.responseText);
                    return;
                }

                resolve(json.url);
            };

            xhr.onerror = () => {
                reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
            };

            const formData = new FormData();
            formData.append('file', blobInfo.blob(), blobInfo.filename());

            xhr.send(formData);
        });

//tinymce初始化
tinymce.init({
            selector: '#mytextarea',
            language: 'zh-Hans',//中文显示
            mobile: {
                theme: 'mobile',
                plugins: ['autosave', 'lists', 'autolink'],
                toolbar: ['undo', 'bold', 'italic', 'styleselect']
            },
            setup: function (editor) {
                editor.on('init', function () {
                    var viewportMeta = document.createElement('meta');
                    viewportMeta.setAttribute('name', 'viewport');
                    viewportMeta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');
                    document.getElementsByTagName('head')[0].appendChild(viewportMeta);
                });
            },
            plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave bdmap indent2em autoresize lineheight formatpainter axupimgs',
            toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
            styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
            table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight formatpainter axupimgs',
            fontsize_formats: '10px 12px 14px 16px 18px 20px 22px 24px 26px 28px 30px 32px 34px 36px 38px 40px',
            width:1000,
            height: 650, //编辑器高度
            min_height: 400,
            images_upload_handler: example_image_upload_handler,
            //上传本地视频方法
            file_picker_callback: function (callback, value, meta) {
                if (meta.filetype === 'file') {
                    callback('https://www.baidu.com/img/bd_logo1.png', { text: 'My text' });
                }
                if (meta.filetype === 'image') {
                    callback('https://www.baidu.com/img/bd_logo1.png', { alt: 'My alt text' });
                }
                // 主要判断 media
                if (meta.filetype === 'media') {
                    // 动态创建上传input,并进行模拟点击上传操作,达到本地上传视频效果。
                    let input = document.createElement('input');//创建一个隐藏的input
                    input.setAttribute('type', 'file');
                    input.setAttribute("accept", ".mp4");
                    let that = this;
                    input.onchange = function(){
                        let file = this.files[0];
                        let fd = new FormData();
                        fd.append("file", file);

                        let xhr = new XMLHttpRequest();
                        xhr.open("POST", ctx + 'common/upload');
                        xhr.onload = function() {
                            if (xhr.status === 200) {
                                let res = JSON.parse(xhr.responseText);
                                let rr = res;
                                // callback 回调的作用是将所选择的视频的url显示在输入框中
                                callback(rr.url);
                            } else {
                                console.error('Error uploading file:', xhr.statusText);
                            }
                        };
                        xhr.onerror = function() {
                            console.error('Error uploading file:', xhr.statusText);
                        };
                        xhr.send(fd);
                    }
                    //触发点击
                    input.click();
                }
            }
        });

效果如下:
在这里插入图片描述
在发布文章中插入图片
在这里插入图片描述

接收上传图片controller

    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = RuoYiConfig.getServerUrl() + fileName;
            System.out.println("url-------"+serverConfig.getUrl());
            System.out.println("fileName-------"+fileName);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值