quill icon indicating copy to clipboard operation
quill copied to clipboard

Call image handler when image is drag and dropped into the editor

Open PaulleDemon opened this issue 1 year ago • 1 comments

Use the below code, then try drag and dropping an image into editor

const quill = new Quill('#editor', {
  toolbar: {
    handlers: {
      image: function() {
        console.log("called")
        let fileInput = this.container.querySelector('input.ql-image[type=file]');
        if (fileInput == null) {
          fileInput = document.createElement('input');
          fileInput.setAttribute('type', 'file');
          fileInput.setAttribute(
            'accept',
            'image/png, image/gif, image/jpeg, image/bmp, image/x-icon'
          );
          fileInput.classList.add('ql-image');
          fileInput.addEventListener('change', () => {
            if (fileInput.files != null && fileInput.files[0] != null) {
              // Do your own stuff here
            }
          });
          this.container.appendChild(fileInput);
        }
        fileInput.click();
      }
    }
  }
});

Expected behavior: The image handler should be called, even if the image is dragged and dropped into the editor

Actual behavior: The image handler is not called, if the image is dragged and dropped into the editor

Quill Version: 2.0.0-dev.4

PaulleDemon avatar Mar 25 '24 18:03 PaulleDemon

Ok while I haven't found a direct solution. So as a workaround, I modified the uploader handler to call the image handler.

Eg:

editor.getModule('uploader').options.handler = (range, files) => {
  
    files.forEach((file) => {
        if (/^image\//.test(file.type)) { // Check if the file is an image
            uploadBlogImage(file) // upload image to server
        } else {
            // something else
        }
    });
}
editor.getModule('uploader').options.mimetypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg']

PaulleDemon avatar Mar 26 '24 06:03 PaulleDemon

This does work to override the native handler, but how would you use it to run in addition to the native handler?

==> Meaning you still want the image to show up in the editor, but want other programmatic things to happen in addition.

mark8044 avatar Jul 06 '24 23:07 mark8044

@mark8044 if you are using the image handler to uplaoad to server, you'll have to get uploaded image URL from server and then insert the image programmatically.

Something like shown below

const range = editor.getSelection(true)
editor.insertText(range.index, '\n')
editor.insertEmbed(range.index + 1, 'image', {src: `${url}`})

PaulleDemon avatar Jul 07 '24 04:07 PaulleDemon

That does work perfectly. thanks

mark8044 avatar Jul 07 '24 06:07 mark8044