KillerCodeMonkey / ngx-quill

Angular (>=2) components for the Quill Rich Text Editor
MIT License
1.79k stars 264 forks source link

Image duplication problem when pasting: base64 and URL server #1956

Closed d4nm0 closed 10 hours ago

d4nm0 commented 10 hours ago

Hello,

I'm having a problem with the Quill editor when I paste an image. Currently, the image is inserted twice: once as a URL (after downloading it from my server) and once as a base64 image. My aim is to prevent the image from being inserted as a base64 image and to keep only the URL of the image uploaded to my server.

I've tried to handle this event using a paste listener and a clipboard.addMatcher, but the image continues to be inserted in base64, despite my attempts to prevent it.

I've attached the code I use to detect and handle pasted images. My problem only occurs when I copy and paste an image into the editor. I can't stop Quill from adding the base64 version in addition to the URL.

Do you have any suggestions for solving this problem?

Thanks in advance for your help!

` onEditorCreated(quill: any) { this.quill = quill; // Référence de l'instance Quill

// Écouteur d'événement pour capturer les images collées
this.quill.root.addEventListener('paste', async (e: ClipboardEvent) => {
  console.log('paste');
  if (e.clipboardData) {
    const items = e.clipboardData.items;

    // Déclaration d'un flag pour éviter l'insertion en base64
    let imageInserted = false;

    for (let i = 0; i < items.length; i++) {
      const item = items[i];

      // Vérifiez si l'élément est une image
      if (item.type.startsWith('image/')) {
        e.preventDefault();  // Empêcher l'insertion par défaut (base64)

        const file = item.getAsFile();
        if (file) {
          const formData = new FormData();
          formData.append('upload', file);
          formData.append('file_type', file.type);
          formData.append('system', 'attachment');
          formData.append('project_id', '0');
          formData.append('project_ref', '0');
          formData.append('profile_id', '0');
          formData.append('profile_ref', '0');

          try {
            const response = await fetch(this.imageServer, {
              method: 'POST',
              body: formData,
            });

            if (!response.ok) {
              throw new Error(`Erreur ${response.status}: ${response.statusText}`);
            }

            const data = await response.json();
            const imageUrl = data.url;

            // Insérer l'image téléchargée dans l'éditeur
            const range = this.quill.getSelection();
            this.quill.insertEmbed(range.index, 'image', imageUrl);
            this.onChange(this.quill.root.innerHTML);  // Mettre à jour l'HTML

            // Marquer l'image comme insérée pour ne pas la traiter à nouveau
            imageInserted = true;
          } catch (error) {
            console.error('Erreur lors du téléchargement de l\'image collée :', error);
          }
        }
      }
    }

    // Si une image a été insérée via le collage, on empêche le traitement par le matcher
    if (imageInserted) {
      return; // Ne rien faire de plus dans ce cas
    }
  }
});

// Matcher pour détecter les images et éviter l'insertion par défaut en base64
this.quill.clipboard.addMatcher(Node.ELEMENT_NODE, (node: any, delta: any) => {
  if (node.tagName === 'IMG') {
    const imageUrl = node.getAttribute('src');

    // Si l'image est en base64, la supprimer du delta
    if (imageUrl && imageUrl.startsWith('data:image/')) {
      console.log('Image en base64 détectée, suppression');
      const modifiedDelta = delta.delete(delta.length);
      return modifiedDelta;
    }

    // Si l'image est une URL valide, la garder
    console.log('Image URL valide détectée:', imageUrl);
    return delta;
  }
  return delta;
});

}`

KillerCodeMonkey commented 10 hours ago

sorry, but i will not help by custom implementation issues.

this problem does not occur per default. So please create a stackoverflow entry or ask at the quilljs repo.

i quick checked your problem. Maybe just overwrite the ImageBlot with your handling. so you have only one image format/blot with your paste handling.

Thanks