CKEditor 5通过外部URL插入图像

时间:2018-08-01 21:45:17

标签: javascript image asp.net-core ckeditor ckeditor5

我想知道如何仅通过其网址插入图片(用户从其他网站获取图片)。因此,我需要在CKEditor 5中实现简单的 img src =“” 。问题是默认情况下,编辑器需要我上传图像,而我需要通过外部URL插入。

我已经阅读了许多相关主题(123),但没有发现与我类似的问题。我什至不需要特殊的按钮,也许我可以通过某种方式在CKEditor中键入 img src =“ myurl” (直接在编辑器中键入对我不起作用),然后使其成为将 @ Html.Raw(Model.Text)应用到我从CKeditor文本区域存储在数据库中的整个文本之后,感觉就像html代码一样。

这就是将数据从编辑器插入到webpge后得到的。我认为这是因为出于安全原因,标签被视为像文本一样。

enter image description here

P.S。当我单击对话框中的来自网络的链接时,Stackoverflow图像插入工具允许按其网址上传图像。所以我想要CKEditor 5中的类似功能。

将非常感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

在其文档中,有一个关于如何实现此功能的非常简单明了的解释:https://ckeditor.com/docs/ckeditor5/latest/framework/guides/creating-simple-plugin.html

import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';

import Essentials from '@ckeditor/ckeditor5-essentials/src/essentials';
import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
import Bold from '@ckeditor/ckeditor5-basic-styles/src/bold';
import Italic from '@ckeditor/ckeditor5-basic-styles/src/italic';
import Image from '@ckeditor/ckeditor5-image/src/image';
import ImageCaption from '@ckeditor/ckeditor5-image/src/imagecaption';

import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';

import imageIcon from '@ckeditor/ckeditor5-core/theme/icons/image.svg';

class InsertImage extends Plugin {
    init() {
        const editor = this.editor;

        editor.ui.componentFactory.add( 'insertImage', locale => {
            const view = new ButtonView( locale );

            view.set( {
                label: 'Insert image',
                icon: imageIcon,
                tooltip: true
            } );

            // Callback executed once the image is clicked.
            view.on( 'execute', () => {
                const imageUrl = prompt( 'Image URL' );

                editor.model.change( writer => {
                    const imageElement = writer.createElement( 'image', {
                        src: imageUrl
                    } );

                    // Insert the image in the current selection location.
                    editor.model.insertContent( imageElement, editor.model.document.selection );
                } );
            } );

            return view;
        } );
    }
}

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        plugins: [ Essentials, Paragraph, Bold, Italic, Image, InsertImage, ImageCaption ],
        toolbar: [ 'bold', 'italic', 'insertImage' ]
    } )
    .then( editor => {
        console.log( 'Editor was initialized', editor );
    } )
    .catch( error => {
        console.error( error.stack );
    } );

最终结果:

enter image description here

我希望它会有所帮助。 :)