Coller des fichiers

Harry Theodoulou
Harry Theodoulou

Le collage de fichiers dans le navigateur consiste à utiliser l'événement paste de HTMLElement.

Utiliser l'événement paste de HTMLElement

Dans un premier temps, vous ajoutez un écouteur d'événements pour l'événement paste au niveau de l'élément souhaité. Il s'agit généralement du niveau document. Aucun élément spécifique n'a donc besoin d'être sélectionné. Ensuite, utilisez l'API Clipboard, qui vous donne accès au champ clipboardData de l'événement paste de HTMLElement, dont vous pouvez ensuite itérer la liste files. En fonction du type MIME de chacun des fichiers collés, vous pouvez décider de l'afficher à l'écran, comme dans le cas d'une image ou d'une vidéo, ou de coller le contenu textuel du fichier, par exemple, dans un élément textarea (dans le cas d'un fichier texte).

Navigateurs pris en charge

  • 66
  • 79
  • 63
  • 13.1

Source

document.addEventListener('paste', async (e) => {
  // Prevent the default behavior, so you can code your own logic.
  e.preventDefault();
  if (!e.clipboardData.files.length) {
    return;
  }
  // Iterate over all pasted files.
  Array.from(e.clipboardData.files).forEach(async (file) => {
    // Add more checks here for MIME types you're interested in,
    // such as `application/pdf`, `video/mp4`, etc.
    if (file.type.startsWith('image/')) {
      // For images, create an image and append it to the `body`.
      const img = document.createElement('img');
      const blob = URL.createObjectURL(file);
      img.src = blob;
      document.body.append(img);
    } else if (file.type.startsWith('text/')) {
      // For text files, read the contents and output it into a `textarea`.
      const textarea = document.createElement('textarea');
      textarea.value = await file.text();
      document.body.append(textarea);
    }
  });
});

Complément d'informations

Démonstration

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>How to paste files</title>
  </head>
  <body>
    <h1>How to paste files</h1>
    <p>Hit <kbd>⌘</kbd> + <kbd>v</kbd> (for macOS) or <kbd>ctrl</kbd> + <kbd>v</kbd>
      (for other operating systems) to paste image or text file(s) anywhere in this page.
    </p>
  </body>
</html>

CSS


        html {
  box-sizing: border-box;
  font-family: system-ui, sans-serif;
  color-scheme: dark light;
}

*, *:before, *:after {
  box-sizing: inherit;
}

body {
  margin: 1rem;
}

img {
  height: auto;
  max-width: 100%;
  display: block;
}
        

JS


        document.addEventListener('paste', async (e) => {
  // Prevent the default behavior, so you can code your own logic.
  e.preventDefault();
  if (!e.clipboardData.files.length) {
    return;
  }
  // Iterate over all pasted files.
  Array.from(e.clipboardData.files).forEach(async (file) => {
    // Add more checks here for MIME types you're interested in,
    // such as `application/pdf`, `video/mp4`, etc.
    if (file.type.startsWith('image/')) {
      // For images, create an image and append it to the `body`.
      const img = document.createElement('img');
      const blob = URL.createObjectURL(file);
      img.src = blob;
      document.body.append(img);
    } else if (file.type.startsWith('text/')) {
      // For text files, read the contents and output it into a `textarea`.
      const textarea = document.createElement('textarea');
      textarea.value = await file.text();
      document.body.append(textarea);
    }
  });
});