使用 Javascript 将文件加载到 CKEditor 文本区域

Load file into CKEditor textarea using Javascript

正在尝试使用输入按钮和 javascript 将文件加载到 CKEditor 4 文本区域。这些文件包含简单的 HTML 代码并具有扩展名 .inc 和 .txt

我的作品有效,但只有在使用浏览器 back/forward 按钮(学生错误地发现)之后。使用本地驱动器的输入加载文件,textarea 变为空白,但加载的文件仅在使用浏览器 back/forward 按钮后出现?

这是我们正在使用的HTML:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://cdn.ckeditor.com/4.5.11/standard/ckeditor.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    </head>
<body>

        <textarea name="editor1" id="editor1" rows="10" cols="80">
            Placeholder text...
        </textarea>
        <script>
            CKEDITOR.replace( 'editor1' );
        </script>

        <input name="file" type="file" id="files" class="form-control" value="">

        <script type="text/javascript">
                function readTextFile(file, callback, encoding) {
            var reader = new FileReader();
            reader.addEventListener('load', function (e) {
                callback(this.result);
            });
            if (encoding) reader.readAsText(file, encoding);
            else reader.readAsText(file);
        }

        function fileChosen(input, output) {
            if (input.files && input.files[0]) {
                readTextFile(
                    input.files[0],
                    function (str) {
                        output.value = str;
                    }
                );
            }
        }

        $('#files').on('change', function () {
        var result = $("#files").text();
        //added this below testing
        fileChosen(this, document.getElementById('editor1'));
        CKEDITOR.instances['editor1'].setData(result);
        });
        </script>

</body>
</html>

也放在JSFiddle

W3schools

仅供参考:浏览器 back/forward mystery 在以上两个站点上不起作用,仅当我在本地或服务器上使用时才起作用。

在课堂上尝试解决这个问题 3 天后,我来这里征求意见。我们花了几个小时尝试在这里和许多网站上找到的不同方法。

安全性不是输入文件限制的问题,仅在课堂上用于培训purposes/examples。

有人吗?

好的,我成功了。 为了替换文本,您需要在 CKEDITOR 实例 上调用 setData(str); 方法,而不是在 DOM 元素上调用。您还需要告诉编辑器更新 ("redraw") 它的内容。

所以:

fileChosen

function fileChosen(input, output) {
        if ( input.files && input.files[0] ) {
            readTextFile(
                input.files[0],
                function (str) {
                    output.setData(str); // We use the setData() method
                    output.updateElement(); // Then we tell the CKEditor instance to update itself
                }
            );
        }
    }

文件输入更改

$('#files').on('change', function () {
    var result = $("#files").text();
    fileChosen(this,  CKEDITOR.instances.editor1); // We pass the CKEDITOR instance, not the DOM element
});

我还进行了更改,例如在 CKEDITOR javascript 文件之前导入 jQuery。

查看结果in this fiddle