【问题标题】:How to add image from computer in Quill JS?如何在 Quill JS 中从计算机添加图像?
【发布时间】:2016-06-24 05:13:04
【问题描述】:

可以从 url 将图像添加到 quill JS 编辑器中,但无法像所有传统的富文本编辑器那样从计算机添加图像。

有什么方法可以达到这个目的吗?

【问题讨论】:

标签: javascript quill


【解决方案1】:

您可以执行以下操作:

quill.getModule("toolbar").addHandler("image", () => {
        this.selectLocalImage();
    });

function selectLocalImage() {
    var input = document.createElement("input");
    input.setAttribute("type", "file");
    input.click();
    // Listen upload local image and save to server
    input.onchange = () => {
        const file = input.files[0];
        // file type is only image.
        if (/^image\//.test(file.type)) {
            this.saveToServer(file, "image");
        } else {
            console.warn("Only images can be uploaded here.");
        }
    };
}

function saveToServer(file) {
    // Upload file to server and get the uploaded file url in response then call insertToEditor(url) after getting the url from server
}

function insertToEditor(url) {
    // push image url to editor.
    const range = quill.getSelection();
    quill.insertEmbed(range.index, "image", url);
}

【讨论】:

    【解决方案2】:

    这很简单。只需添加一个带有 ql-image 类的按钮。

    下面的例子:

    <div id="toolbar" class="toolbar">
       <span class="ql-formats">
          <button class="ql-image"></button>
       </span>
    </div>
    

    最后,实例化 Quill 并将工具栏容器设置为您的工具栏元素:

    var quill = new Quill('#editor', {
                modules: {
                    toolbar: {
                        container: '#toolbar'
                    }
                },
                theme: 'snow'
            });
    

    这会将图像作为 img 元素上的 base 64 编码字符串添加到内容可编辑区域。

    【讨论】:

    • 我只是通过将它松散地放入我的代码中来测试这段代码,它完美地工作,除了它用太大的 413 请求实体引爆我的端点。我以前遇到过这个问题,我应该能够增加大小限制。感谢您的代码。
    猜你喜欢
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 2023-03-27
    相关资源
    最近更新 更多