2

It is possible to add a image into quill JS editor from a url but can't find a way to add an image from computer like all the traditional rich text editors do.

Is there any way that serves this purpose?

Andrew Li
  • 55,805
  • 14
  • 125
  • 143

2 Answers2

4

You can do the following:

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);
}
1

This is simple. Simply add a button with a class of ql-image.

Example below:

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

Finally, instantiate Quill with the toolbar container set to your toolbar element:

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

This will add the image to the content editable area you have as a base 64 encoded string on an img element.

Daniel Lane
  • 2,575
  • 2
  • 18
  • 33
  • I just tested this code by loosely throwing it into my code, and it worked flawlessly except its detonating my endpoint with 413 request entity too large. I've had this issue before and I should be able to just increase the size limit. Thanks for the code. – agm1984 Sep 06 '17 at 05:19